I have a database which contains two dates which I am concerned with.
StartDate +
EndDate
These dates are stored in the following format:
2008-06-23 00:00:00.000
I need to add a piece of dynamic SQL to only bring back dates which fall in the current financial year.
so for example 01/04/2011 - 31/03/2012 would be this financial year.
Therfore any record whos enddate is within these dates, or is NULL is classed as 'active'
The year part will need to be dynamic so that as soon as it hits 1st April 2012 we move into the new financial year and will be bringing data back from 01/04/2012 - 31/03/13 and so on.
Can suggest some code or point out any rules I have overlooked?
Try:
...
where StartDate >=
case
when month(getdate()) > 3
then convert(datetime, cast(year(getdate()) as varchar) + '-4-1')
else
convert(datetime, cast(year(getdate()) - 1 as varchar) + '-4-1')
end
and (EndDate is null or EndDate <
case
when month(getdate()) > 3
then convert(datetime, cast(year(getdate()) + 1 as varchar) + '-4-1')
else
convert(datetime, cast(year(getdate()) as varchar) + '-4-1')
end)
Here we go :)
Dynamic solution,
DECLARE #MyDate DATETIME
SET #MyDate = getDate()
DECLARE #StartDate DATETIME
DECLARE #EndDate DATETIME
SET #StartDate = DATEADD(dd,0, DATEDIFF(dd,0, DATEADD( mm, -(((12 + DATEPART(m, #MyDate)) - 4)%12), #MyDate ) - datePart(d,DATEADD( mm, -(((12 + DATEPART(m, #MyDate)) - 4)%12),#MyDate ))+1 ) )
SET #EndDate = DATEADD(ss,-1,DATEADD(mm,12,#StartDate ))
SELECT #StartDate,#EndDate
Create a Finacial_Year lookup table containing the fields financial_year_start and financial_year_end.
Populate it with the next 50 years of data (easy to do using a spread sheet to calulate the dates).
Join your table to the lookup table using enddate
SELECT ...
FROM Your_Table LEFT JOIN Financial_Year
ON Your_Table.enddate BETWEEN Financial_Year.financial_year_start
AND Financial_Year.financial_year_end
WHERE Your_Table.enddate IS NULL -- Active
OR (getdate() BETWEEN Financial_Year.financial_year_start
AND Financial_Year.financial_year_end)
The current financial will change automatically when the current date falls between the next two dates.
BTW the UK financial year runs from 06-04-YYYY to 05-04-YYYY, not the 1st to the 31st.
Related
I need to find anniversary date and anniversary year of employees and send email in every 14 days.But I have a problem with last week of December when using the following query if start date and end date are in different years.
Select * from Resource
where (DATEPART(dayofyear,JoinDate)
BETWEEN DATEPART(dayofyear,GETDATE())
AND DATEPART(dayofyear,DateAdd(DAY,14,GETDATE())))
Instead of comparing to a dayofyear (which resets to zero at jan 1st and is the reason your query breaks within 14 days of the end of the year) you could update the employee's joindate to be the current year for the purpose of the query and just compare to actual dates
Select * from Resource
-- Add the number of years difference between joinDate and the current year
where DATEADD(year,DATEDIFF(Year,joinDate,GetDate()),JoinDate)
-- compare to range "today"
BETWEEN GetDate()
-- to 14 days from today
AND DATEADD(Day,14,GetDate())
-- duplicate for following year
OR DATEADD(year,DATEDIFF(Year,joinDate,GetDate())+1,JoinDate) -- 2016-1-1
BETWEEN GetDate()
AND DATEADD(Day,14,GetDate())
Test query:
declare #joindate DATETIME='2012-1-1'
declare #today DATETIME = '2015-12-26'
SELECT #joinDate
where DATEADD(year,DATEDIFF(Year,#joinDate,#today),#JoinDate) -- 2015-1-1
BETWEEN #today -- 2015-12-26
AND DATEADD(Day,14,#today) -- 2016-01-09
OR DATEADD(year,DATEDIFF(Year,#joinDate,#today)+1,#JoinDate) -- 2016-1-1
BETWEEN #today -- 2015-12-26
AND DATEADD(Day,14,#today) -- 2016-01-09
(H/T #Damien_The_Unbeliever for a simple fix)
The above correctly selects the joinDate which is in the first week of Jan (note I've had to fudge #today as Ive not managed to invent time travel).
The above solution should also solve the issue with leap years that was hiding in your original solution.
Update
You expressed in comments the requirement to select AnniversaryDate and Years of service, you need to apply some CASE logic to determine whether to add 1 (year or date) to your select
select *,
CASE
WHEN DATEADD(YEAR,DATEDIFF(Year,JoinDate,GETDATE()),JoinDate) < GetDate()
THEN DATEDIFF(Year,JoinDate,GETDATE())+1
ELSE DATEDIFF(Year,JoinDate,GETDATE())
END as [Years],
CASE WHEN DATEADD(YEAR,DATEDIFF(Year,JoinDate,GETDATE()),JoinDate) < GetDate()
THEN DATEADD(YEAR,DATEDIFF(Year,JoinDate,GETDATE())+1,JoinDate)
ELSE DATEADD(YEAR,DATEDIFF(Year,JoinDate,GETDATE()),JoinDate)
end as [AnniversaryDate]
.... // etc
You could do this:
Select * from Resource
where DATEPART(dayofyear,JoinDate)
BETWEEN DATEPART(dayofyear,GETDATE())
AND DATEPART(dayofyear,DateAdd(DAY,14,GETDATE()))
OR
DATEPART(dayofyear,JoinDate)
BETWEEN (DATEPART(dayofyear,GETDATE()) + 365)
AND (DATEPART(dayofyear,DateAdd(DAY,14,GETDATE())) + 365)
Try this:
DECLARE #Today DATE = GETDATE() --'12/25/2013'
DECLARE #Duration INT = 14
;WITH Recur AS
(
SELECT #Today AS RecurDate
UNION ALL
SELECT DATEADD(DAY, 1, RecurDate)
FROM Recur
WHERE DATEDIFF(DAY, #Today, RecurDate)+1 < #Duration
)
SELECT
r.*
FROM
Resource r
JOIN Recur
ON CONVERT(VARCHAR(5), JoinDate, 101) = CONVERT(VARCHAR(5), RecurDate, 101)
WHERE JoinDate < #Today
You can use the SQL DATEADD() function with week number parameter
Here is how you can use it:
DECLARE #date date = getdate()
Select * from Resource
where
JoinDate BETWEEN #date AND DATEADD(ww,2,#date)
So I have this code, this is for grabbing data for the last 11 month of sale including the current month, make it a whole year. What do I have to do to change it to grabbing data for the last 12 months plus current month? I know I have to change something on the right(select period)... but not sure
In this one, the left function shows how to get the current year (2014 ) minus 1 to give 2013.. but I don't understand the right function, what does 2 mean?
Thanks
period <= (
SELECT Period
FROM dbo.FiscalDates
WHERE (Date = CONVERT(varchar(10), GETDATE(), 102))) and period >= (
convert(varchar, left((
SELECT Period
FROM dbo.FiscalDates
WHERE (Date = CONVERT(varchar(10), GETDATE(), 102))),4)-1)+'-'+
convert(varchar, right((
SELECT Period
FROM dbo.FiscalDates
WHERE (Date = CONVERT(varchar(10), GETDATE(), 102))),2)))
group by prodnum, period, WhseNum
Whoah buddy I think you may be overcomplicating things here. If you want to get data for the past X number of months then just use DATEADD it's a very useful function.
All you need to do then is
select
YourColumns
FROM YourTable
WHERE YourDate >= DATEADD(MONTH, -13, CAST(GETDATE() AS DATE))
and bam there you go.
DECLARE
#FormYear AS INT,
#FormMonth AS INT,
#ToYear AS INT,
#ToMonth AS INT,
#FromDate AS DATE,
#ToDate AS DATE
SET #FormYear=YEAR(DATEADD(DAY, -365, GETDATE()))
SET #FormMonth=MONTH(DATEADD(DAY, -365, GETDATE()))
SET #ToYear=YEAR(GETDATE())
SET #ToMonth=MONTH(GETDATE())
SET #FromDate= CAST(CAST(#FormMonth AS VARCHAR) +'-'+'01'+ '-' +CAST(#FormYear AS VARCHAR) AS DATE)
SET #ToDate= CAST(CAST(#ToMonth AS VARCHAR) +'-' + '01'+'-' + CAST(#ToYear AS VARCHAR) AS DATE)
After that, just select-
YourDateField Between #FormDate AND #ToDate
I need to generate either a column in a query or a temp table (not sure which one is required)
so that I can have a list of dates that are on Saturday that fall within a given date range.
This list will be used in a join to associate records with weeks.
What are my options?
Sample Input:
From: 03/01/2013
To: 04/30/2013
Results:
Week Ending
- 03/02/2013
- 03/09/2013
- 03/16/2013
- 03/23/2013
- 03/30/2013
- 04/06/2013
- 04/13/2013
- 04/20/2013
- 04/27/2013
- 05/04/2013
Current code:
create table #TBL7(YEAR INT, WEEKNUMBER INT, STARTDATE DATETIME, ENDDATE DATETIME)
begin
declare #startdate datetime
, #enddate datetime
, #ctr int
SET #startdate = CAST(2013 AS VARCHAR)+ '/01/01'
SET #enddate = CAST(2013 AS VARCHAR) + '/12/31'
SET #ctr = 0
WHILE #enddate >= #startdate
BEGIN
SET #ctr = #ctr + 1
INSERT INTO #TBL7
values(year(#startdate), #ctr, #startdate, #startdate + 6)
SET #startdate = #startdate + 7
END
end
select * from #TBL7
First, create a calendar table. Then you have a very simple query:
select [Date]
from dbo.Calendar
where DayOfWeek = 'Saturday' and [Date] between '20130301' and '20130430'
A calendar table is almost always the best approach to working with dates because you're working with data, not code, so you can see it's correct and there's no cryptic code to maintain.
This is Oracle code. Sorry I do not know how to convert this to SQL SERVER. Should not be very hard. All you need is to use proper functions in place of to_date() and to_char(), and calc the difference between start and end date, e.g. (end_date-start_date)+1:
WITH data(r, some_date) AS
(
SELECT 1 r, to_date('03/01/2013', 'MM/DD/YYYY') some_date FROM dual
UNION ALL
SELECT r+1, to_date('03/01/2013', 'MM/DD/YYYY')+r FROM data WHERE r < 61 -- (end_date-start_date)+1
)
SELECT some_date
, To_Char(some_date, 'DY') wk_day
FROM data
WHERE To_Char(some_date, 'DY') = 'SAT'
/
SOME_DATE WK_DAY
--------------------
3/2/2013 SAT
3/9/2013 SAT
3/16/2013 SAT
3/23/2013 SAT
3/30/2013 SAT
4/6/2013 SAT
4/13/2013 SAT
4/20/2013 SAT
4/27/2013 SAT
This should work:
WITH cteWeeks (WeekEnding) As
(
-- Find the Saturday of the first week.
-- Need to allow for different DATEFIRST settings:
SELECT
CASE
WHEN DatePart(dw, DateAdd(day, ##datefirst, #StartDate)) = 7 THEN #StartDate
ELSE DateAdd(day, 7 - DatePart(dw, DateAdd(day, ##datefirst, #StartDate)), #StartDate)
END
UNION ALL
SELECT
DateAdd(day, 7, WeekEnding)
FROM
cteWeeks
WHERE
WeekEnding < #EndDate
)
SELECT
WeekEnding
FROM
cteWeeks
;
http://www.sqlfiddle.com/#!3/d41d8/12095
DECLARE #MyDate Datetime
set #MyDate = GETDATE();
WITH cte AS
(SELECT #MyDate AS AllDates,
1 AS [count_all_days],
CASE WHEN DATENAME(dw, DATEADD(dd, - 1, #MyDate)) IN ('Saturday', 'Sunday') THEN 1 ELSE 0 END AS [count_week_days]
UNION ALL
SELECT DATEADD(dd, - [count_all_days], #MyDate),
[count_all_days] + 1,
CASE WHEN DATENAME(dw, DATEADD(dd, - [count_all_days], #MyDate)) IN ('Saturday', 'Sunday') THEN [count_week_days] + 1 ELSE [count_week_days]
END
FROM cte
WHERE [count_all_days] - [count_week_days] < 16
)
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, AllDates))
FROM cte left join EmpLog ON AllDates = EmpLog.Date
left JOIN Holiday ON AllDates = Holiday.HolDate
WHERE DATENAME(dw, AllDates) NOT IN ('Saturday', 'Sunday')AND AllDates NOT IN (Select EmpLog.Date from EmpLog where EmpLog.EmpID = 1)and Holiday.HolDate IS NULL
This SQL query displays the current date and the previous 16 days. wherein those dates are not equal to the existing date on the HOLIDAY table and in the EMPLOG table.
My problem is this query works on SQL Server 2008 well but when I tried it on SQL Server 2005 it only displays the current date and the previous 16 days even though some days are in HOLIDAY and EMPLOG table.
Can someone help me please? thanks!
Try casting your Date variables -- you're comparing GetDate to Dates that don't necessarily have the same time:
left JOIN Holiday ON CAST(AllDates as Date) = CAST(Holiday.HolDate as Date)
Wrap that with all your dates and it should work. Take a look at this SQL Fiddle. In this example, I've only added 1 holiday, 1/21/2013 (MLK).
EDIT --
Try using convert(varchar, getdate(), 101) to CAST the date since SQL Server 2005 doesn't support the Date type.
Here is the updated SQL:
left JOIN Holiday ON convert(varchar, AllDates, 101) = convert(varchar, Holiday.HolDate, 101)
Do that on all your date conversions. Here is the updated Fiddle.
Thanks #user148298 for pointing this out.
Good luck.
There appears to be some differences between dates in 2008 and 2005. You have to set your database compatibility. See the following article:
http://msdn.microsoft.com/en-us/library/bb510680.aspx
Try changing the #MyDate initialisation to:
set #MyDate = Convert(DATETIME(CONVERT(VARCHAR(10), GETDATE(), 121) + ' 00:00:00', 121);
Explanation: By doing this you make the #MyDate as a "midnight today", instead of "today with current time". That way it would better join with your tables.
Assumption: The dates in your holiday tables are stored as "midnight"
I have to calculate all the invoices which have been paid in the first 'N' days of a month. I have two tables
. INVOICE: it has the invoice information. The only field which does matter is called 'datePayment'
. HOLYDAYS: It is a one column table. Entries at this table are of the form "2009-01-01",
2009-05-01" and so on.
I should consider also Saturdays and Sundays
(this might be not a problem because I could insert those days at the Hollidays table in order to consider them as hollidays if neccesary)
The problem is to calculate which is the 'payment limit'.
select count(*) from invoice
where datePayment < PAYMENTLIMIT
My question is how to calculate this PAYMENTLIMIT. Where PAYMENTLIMIT is 'the fifth working day of every month'.
The query should be run under Mysql and Oracle therefore standard SQL should be used.
Any hint?
EDIT
In order to be consistent with the title of the question the pseudo-query should the read as follows:
select count(*) from invoice
where datePayment < FIRST_WORKING_DAY + N
then the question can be reduced to calculate the FIRST_WORKING_DAY of every month.
You could look for the first date in a month, where the date is not in the holiday table and the date is not a weekend:
select min(datePayment), datepart(mm, datePayment)
from invoices
where datepart(dw, datePayment) not in (1,7) --day of week
and not exists (select holiday from holidays where holiday = datePayment)
group by datepart(mm, datePayment) --monthnr
Something like this might work:
create function dbo.GetFirstWorkdayOfMonth(#Year INT, #Month INT)
returns DATETIME
as begin
declare #firstOfMonth VARCHAR(20)
SET #firstOfMonth = CAST(#Year AS VARCHAR(4)) + '-' + CAST(#Month AS VARCHAR) + '-01'
declare #currDate DATETIME
set #currDate = CAST(#firstOfMonth as DATETIME)
declare #weekday INT
set #weekday = DATEPART(weekday, #currdate)
-- 7 = saturday, 1 = sunday
while #weekday = 1 OR #weekday = 7
begin
set #currDate = DATEADD(DAY, 1, #currDate)
set #weekday = DATEPART(weekday, #currdate)
end
return #currdate
end
I'm not 100% sure about whether the "weekday" numbers are fixed or might depend on your locale on your SQL Server. Check it out!
Marc
Rather than a Holidays table of days to exclude, we use the calendar table approach: one row for every day the application will ever need (thirty years spans a modest 11K rows). So not only does it have an is_weekday column, it has other things relevant to the enterprise e.g. julianized_date. This way, every possible date would have a ready-prepared value for first_working_day_this_month and finding it involves a simple lookup (which SQL products tend to be optimized for!) rather than 'calculating' it each time on the fly.
We have dates table in our application (filled with all dates and date parts for some tens of years), what allows various "missing" date manipulations, like (in pseudo-sql):
select min(ourdates.datevalue)
from ourdates
where ourdates.year=<given year> and ourdates.month=<given month>
and ourdates.isworkday
and not exists (
select * from holidays
where holidays.datevalue=ourdates.datevalue
)
Ok, at a first stab, you could put the following code into a UDF and pass in the Year and Month as variables. It can then return TestDate which is the first working day of the month.
DECLARE #Month INT
DECLARE #Year INT
SELECT #Month = 5
SELECT #Year = 2009
DECLARE #FirstDate DATETIME
SELECT #FirstDate = CONVERT(varchar(4), #Year) + '-' + CONVERT(varchar(2), #Month) + '-' + '01 00:00:00.000'
DROP TABLE #HOLIDAYS
CREATE TABLE #HOLIDAYS (HOLIDAY DateTime)
INSERT INTO #HOLIDAYS VALUES('2009-01-01 00:00:00.000')
INSERT INTO #HOLIDAYS VALUES('2009-05-01 00:00:00.000')
DECLARE #DateFound BIT
SELECT #DateFound = 0
WHILE(#DateFound = 0)
BEGIN
IF(
DATEPART(dw, #FirstDate) = 1
OR
DATEPART(dw, #FirstDate) = 1
OR
EXISTS(SELECT * FROM #HOLIDAYS WHERE HOLIDAY = #FirstDate)
)
BEGIN
SET #FirstDate = DATEADD(dd, 1, #FirstDate)
END
ELSE
BEGIN
SET #DateFound = 1
END
END
SELECT #FirstDate
The things I don`t like with this solution though are, if your holidays table contains all days of the month there will be an infinite loop. (You could check the loop is still looking at the right month) It relies upon the dates being equal, eg all at time 00:00:00. Finally, the way I calculate the 1st of the month past in using string concatenation was a short cut. There are much better ways of finding the actual first day of the month.
Gets the first N working days of each month of year 2009:
select * from invoices as x
where
datePayment between '2009-01-01' and '2009-12-31'
and exists
(
select
1
from invoices
where
-- exclude holidays and sunday saturday...
(
datepart(dw, datePayment) not in (1,7) -- day of week
/*
-- Postgresql and Oracle have programmer-friendly IN clause
and
(datepart(yyyy,datePayment), datepart(mm,datePayment))
not in (select hyear, hday from holidays)
*/
-- this is the MSSQL equivalent of programmer-friendly IN
and
not exists
(
select * from holidays
where
hyear = datepart(yyyy,datePayment)
and hmonth = datepart(mm, datePayment)
)
)
-- ...exclude holidays and sunday saturday
-- get the month of x datePayment
and
(datepart(yyyy, datePayment) = datepart(yyyy, x.datePayment)
and datepart(mm, datePayment) = datepart(mm, x.datePayment))
group by
datepart(yyyy, datePayment), datepart(mm, datePayment)
having
x.datePayment < MIN(datePayment) + #N -- up to N working days
)
Returns the first Monday of the current month
SELECT DATEADD(
WEEK,
DATEDIFF( --x weeks between 1900-01-01 (Monday) and inner result
WEEK,
0, --1900-01-01
DATEADD( --inner result
DAY,
6 - DATEPART(DAY, GETDATE()),
GETDATE()
)
),
0 --1900-01-01 (Monday)
)
SELECT DATEADD(day, DATEDIFF (day, 0, DATEADD (month, DATEDIFF (month, 0, GETDATE()), 0) -1)/7*7 + 7, 0);
select if(weekday('yyyy-mm-01') < 5,'yyyy-mm-01',if(weekday('yyyy-mm-02') < 5,'yyyy-mm-02','yyyy-mm-03'))
Saturdays and Sundays are 5, 6 so you only need two checks to get the first working day