I would like to get last week, last month and last quarter numbers (appended with year number) based on current date.
I have used CONCAT and IIF to get current week/month/quarter numbers and substract it with -1, then check if it is last month/quarter to handle 0 values. Below is the code to get last month and quarter, however I am looking for an optimised code to make it work better. Also getting last week number using code similar to below will have issue with leap/non-leap years.
Last month:
SELECT CONCAT(YEAR(GETDATE()),IIF(DATEPART(MONTH,GETDATE())-1=0,12,DATEPART(MONTH,GETDATE())-1))
Last quarter:
SELECT CONCAT(YEAR(GETDATE()),IIF(DATEPART(QUARTER,GETDATE())-1=0,4,DATEPART(QUARTER,GETDATE())-1))
For example, If my current date is 4th Jan, 2019 -
Last week should return 52 or 53 (based on leap year), Last month should return 12, Last quarter should return 4.
--a week ago
select DATEADD(WEEK, -1, GETUTCDATE())
--the week number(of year), a week ago
select DATEPART(WEEK, DATEADD(WEEK, -1, GETUTCDATE()))
--a month ago
select DATEADD(MONTH, -1, GETUTCDATE())
--the month number, a month ago
select DATEPART(MONTH, DATEADD(MONTH, -1, GETUTCDATE()))
--a quarter ago
select DATEADD(QUARTER, -1, GETUTCDATE())
--the quarter number, a quarter ago
select DATEPART(QUARTER, DATEADD(QUARTER, -1, GETUTCDATE()))
General formula is thus:
Day and time, some PERIOD (week, month, quarter, year etc) ago:
DATEADD(PERIOD_IDENTIFIER, -NUMBER_OF_PERIODS, CURRENT_DATE)
The period that it was then:
DATEPART(PERIOD_IDENTIFIER, DATEADD(PERIOD_IDENTIFIER, -NUMBER_OF_PERIODS, CURRENT_DATE))
ps; every year has 53 weeks, not just leap years, because 365/7 is fractionally over 52
pps; I've used GetUtcDate above because I typically work in UTC as most of my tasks are on multi-country systems and all times are UTC. If you're specifically after something that reports "last X" for your local timezone you might need to use GetDate() instead so that the concept of "this week" and "last week" etc is aligned with your local concept of midnight/day changing
Use this in SQL Server.
select datepart(mm,getdate()-30) as Last_Month
,datepart(qq, getdate()-7) as Last_Quarter
,datepart(wk,getdate()-7) as Last_Week
Related
I would like to determine the growth on sales data from current year WTD with sales data from the same week last year also WTD.
So if this week is Mon, Tue, Wed I am trying to compare Mon, Tue, wed from the same week last year to determine the sales growth. This needs to be dynamic in a sense since it will be running on a daily report, ending WTD on the previous day, through SSRS which will be emailed to various users.
I have done copious amounts of online searching and tried several iterations, all with undesirable affects.
The latest attempt being
SELECT
[storeid],
SUM([Sales]) as [2021SalesWTD]
FROM [dbo].[DailySales2021]
WHERE CONVERT(date, [date]) >= DATEADD(DAY, 1-DATEPART(dw, DATEADD(YEAR,-1,GETDATE())), CONVERT(date, DATEADD(YEAR,-1,GETDATE())))
AND DATEADD(DAY, 8-DATEPART(dw, DATEADD(YEAR,-1,GETDATE())), CONVERT(date, DATEADD(YEAR,-1,GETDATE())))
GROUP BY storeid
This returns the entire week
It might help you to try variable declarations.
Here's something I've drafted up:
--Get today's date, find the day of the week (1 indexed from Sunday) and subtract. Add 2 to balance this offset
DECLARE #MondayThisYear AS DATE = CAST(GETDATE()-DATEPART(WEEKDAY, GETDATE())+2 AS DATE)
--Get the date a year ago. I haven't checked for leap year, add it if you need it
DECLARE #DateLastYear AS DATE = #MondayThisYear-365
--Same idea as MondayThisYear, but using the date from last year
DECLARE #MondayLastYear AS DATE = CAST(#DateLastYear-DATEPART(WEEKDAY, #DateLastYear)+2 AS DATE)
--The number of days that have passed in this working week
DECLARE #WorkingDays AS INT = DATEDIFF(d, #MondayThisYear, GETDATE())
SELECT [insert columns]
FROM [insert table name]
WHERE ([date column]>#MondayThisYear AND [date column]<GETDATE()) OR
([date column]>#MondayLastYear AND [date column]<#MondayLastYear + #WorkingDays)
You might also need to check how I've defined the previous year's dates. In worst case you might get an off-by-one week error, but I don't think that's avoidable given the structure of the calendar.
so I'm kinda stuck with a little query to get the SUM of the time period I want. So it already works but I want that it's automatically between 1 year from now and the beginning of the year.
SELECT SUM(N_EXCL), S_CUSTNO, S_CUSTNAME1, D_INVOICEDATE
from sao.INVOICE_P i
WHERE D_INVOICEDATE > DATEADD (year, -1, getdate ())
AND D_INVOICEDATE < DATEADD (month , -6 ,Getdate () )
GROUP BY S_CUSTNO, S_CUSTNAME1, D_INVOICEDATE
Currently I would have to change the query every month but I try to find a way to avoid it.
Ok. Maybe i wasn't clear enough. My problem is the -6 i have to write down. I want to switch it to a parameter that will automatically change up the date so that i get data from 01.01.2021 - 22.06.2021. So same date, but different year.
If I understand your question, you should be able to do this:
SELECT SUM(N_EXCL), S_CUSTNO, S_CUSTNAME1, D_INVOICEDATE
from sao.INVOICE_P i
WHERE D_INVOICEDATE between DATEADD(year, -1, getdate()) AND DATEFROMPARTS(getdate(), 1, 1)
GROUP BY S_CUSTNO, S_CUSTNAME1, D_INVOICEDATE
So instead of using where and I'm using where between. And I'm checking for todays date last year till 1st of January current year.
If you need from 1st of January previous year you can use:
between DATEFROMPARTS(year(getdate() -1), 1, 1) AND DATEADD(year, -1, getdate())
Tried to add a custom Fiscal Week column to my DimDate table in a query.
Some background: the fiscal year always begins on 02-01 [February 1]. My DimDate tables earliest date goes to January 01, 2008 [01-01-2008]. I looked at previous posts and tried in the code below, except I got 0 for the Week Number for 02-01-2008 and 02-02-2008.
Datediff(wk, CONVERT(DATE, '2008-02-01'), CONVERT(DATE, dbo.DIMDATE.DATE_VALUE)) AS 'FiscalWeek',
If I followed you correctly, you can just offset the date by 1 month:
datepart(wk, dateadd(month, -1, datevalue)) as fiscal_week
Depending on your actual requirement, you might want to try isowk as well.
I am trying to find the week of quarter from a cal_date_d table using sql. My table has cal_date, fiscal quarter start and end date. I also have a column which has the fiscal_week_of_year. and my fiscal year starts from feb.
However the closest query i've got to resolve this issue is below:
select datepart(week, DATEADD(MONTH,-10,cal_date)) - ((DatePart(quarter, DATEADD(MONTH,-10,cal_date))-1) *13),
fiscal_week_of_year,
weekofqtr,
cal_date
from cal_date_d_tst
Now the first week result i am always getting is 0. I am not sure where I am going wrong.
help me out on this one..
If you have fiscal_quarter_start, then doesn't this work?
select 1 + datediff(day, fiscal_quarter_start, cal_date) / 7
This just calculates the number of days into the quarter and divides by 7.
If you base your query on DATEPART(Quarters) use the following.
DATEDIFF(WEEK, DATEADD(MONTH, DATEDIFF(MONTH, 0, '2012-03-17'), 0), '2012-03-17') +1 AS WeekNoMonth,DATEDIFF(WEEK, DATEADD(QUARTER, DATEDIFF(QUARTER, 0, '2012-03-17'), 0), '2012-03-17') +1
Source
This sounded simple but it doesnt work like I thought.
I am trying to track progress for Month to date
Here is my code for MTD
Startdate>=DATEADD(MONTH, DATEDIFF(MONTH, 0, Convert(date, getdate())), 0)
Its extremely simple.
For Last Months Start I use:
Startdate>= DATEADD(month, DATEDIFF(month, -1, getdate()) , 0)
as the start date
and for the current marker I used this:
Enddate>=DATEADD(month, DATEDIFF(month, 0, getdate()-30), 0)+datepart (day,getdate())
Ideally I want to know that if today is the 5th. How many sales took place in that window.
then I want to also know how we did in the same period the last month.
My problem is I find on months with 31 days that follow months with 29 days I have issues.
Is there a function that gives me the same date a month ago ?
dateadd(month, -1, getdate())
i.e. dateadd(month, -1, '20150330') returns '2015-02-28'
If exact day doesn't exist in previous month returns last day of month.