TSQL - SQL Server mumber of the week in Month - sql

I am using the query below to get the number of the week in a month:
datepart(day, datediff(day, 0,TABLE.DATE), 102))/7 * 7)/7 + 1
Now I need to change the script that if a week ends in the next month, it should show 1 instead of 5.
Does anybody can help me?

Using Modulo by 4, you can get the month number 1 instead of 5.
For an example I tested with the 5th week and it result as 1:
DECLARE #TestDate AS DATETIME = '2016-07-29 10:00:00';
SELECT CASE ((DATEPART(DAY, DATEDIFF(DAY, 0, #TestDate)) /7 * 7) /7 + 1) % 4
WHEN 0 THEN 4
ELSE ((DATEPART(DAY, DATEDIFF(DAY, 0, #TestDate)) /7 * 7) /7 + 1) % 4 END
In your query, you wrongly used DATEPART. Actually it requires 2 parameters only.

Related

T-SQL Dynamic date range in WHERE clause (Last fiscal year + year to date)

I'm using the following WHERE clause to only load records from the last fiscal year plus a year to date.
Running without the WHERE clause, it takes 30seconds for 1mil records. With the WHERE clause, I had to stop it after 2hours.
Can you please share your thoughts
WHERE
([schema].[table].[DATE] >= DATEADD
(yy, - 1, DATEADD
(MONTH,(MONTH(GETDATE()) - 1) / 6 * 12 - 6,
CAST(CAST(YEAR(GETDATE()) AS VARCHAR) AS DATETIME)
)
)
)
Declare #PastFiscalYear Date
Set #PastFiscalYear= DATEADD(yy, - 1, DATEADD(MONTH,(MONTH(GETDATE()) - 1) / 6 * 12 - 6,CAST(CAST(YEAR(GETDATE()) AS VARCHAR) AS DATETIME)))
WHERE
([schema].[table].[DATE] >= #PastFiscalYear )
Can you try this
This will bring back data since the previous fiscal year start date. Just change the -3 to what ever your FY offset is. -3 is for October.
[schema].[table].[DATE] >= DATEADD(mm,-3,DATEADD(YEAR, DATEDIFF(YEAR, 0, DATEADD(YEAR, -1, GETDATE())), 0))

How to update date , but date/day should not be sat or sunday

I have a Execute SQL task in SSIS, which updates date in Database to today's date+3. But if suppose today is Thursday say(18/6/2015) and jobs executes then according to update query date in Database will be update to (21/6/2015) out of which 20th and 21st are Sat and Sunday. Instead i would want the date to be updated to 23/6/2015 i.e Tuesday( excluding Sat and Sunday). Please help!
I've made the following SELECT statement which may help you.
Using the DATEPART function you can discover which day of the week a sum of days will be.
DATEPART returns a number representing the day of the week of the date passed as parameter to the function, considering 1 is Sunday and 7 is Saturday.
select CASE
WHEN DATEPART(DW, GETDATE() + 4) = 7 THEN (SELECT GETDATE() + 6)
WHEN DATEPART(DW, GETDATE() + 5) = 1 THEN (SELECT GETDATE() + 5)
END As date
Using this example in an update statement:
UPDATE <your table>
SET dateofanything = (CASE
WHEN DATEPART(DW, GETDATE() + 3) = 7 THEN (SELECT GETDATE() + 5)
WHEN DATEPART(DW, GETDATE() + 3) = 1 THEN (SELECT GETDATE() + 4)
END As date)

default date value of every Friday in SQL Server?

In SQL Server 2008 i want to set a default date value of every Friday to show up in the column when i insert a new record?
ALTER TABLE myTable ADD CONSTRAINT_NAME DEFAULT GETDATE() FOR myColumn
Whats the best way to show every Friday?
I want the default value to be based on the now date then knowing that the next available date is 05-07/2013
I have the following:
dateadd(d, -((datepart(weekday, getdate()) + 1 + ##DATEFIRST) % 7), getdate())
But when passing todays date, it gave me: 2013-06-28 which is actually LAST Friday!, it should be the up and coming Friday!
SELECT DATEADD(day,-3, DATEADD(week, DATEDIFF(week, 0, current_timestamp)+1, 0)) AS LastFridayDateOfWeek
Gets the last date of current week (sunday) then subtracts 3 from that to get Friday.
Replace current_timestamp if you need a different dates friday.
EDIT:
I thought about this a bit, and if the above (Friday THIS WEEK, so for Saturday it gives the previous date) does not work, you could easily use a reference date set like so:
DATEADD(DAY,7 + DATEDIFF(day,'20100109',#checkDateTime)/7*7,'20100108') as FridayRefDate
Same thing but with no hard coded Friday/Saturday in it:
DATEADD(DAY,7 + DATEDIFF(day,DATEADD(wk, DATEDIFF(wk,0,#checkDateTime),5),#checkDateTime)/7*7,DATEADD(wk, DATEDIFF(wk,0,#checkDateTime), 4))
So for 20100109 is a Friday.
SET #checkDateTime = '2012-01-14 3:34:00.000'
SELECT DATEADD(DAY,7 + DATEDIFF(day,'20100109',#checkDateTime)/7*7,'20100108') as FridayRefDate
it returns "2012/1/20"
But for SET #checkDateTime = '2012-01-13 3:34:00.000' it returns "2012/1/13"
If your current query gives you last Friday, the easiest thing to do is simply to add 7 to it:
select dateadd(d, 7-((datepart(weekday, getdate()) + 1 + ##DATEFIRST) % 7), getdate())
------------------^
SELECT CONVERT(DATE, ( CASE WHEN DATEPART(dw, GETDATE()) - 6 <= 0
THEN DATEADD(dd,
( DATEPART(dw, GETDATE()) - 6 ) * -1,
GETDATE())
ELSE DATEADD(dd, ( DATEPART(dw, GETDATE()) ) - 1,
GETDATE())
END )) AS NearestFriday
Just add 7 to the formula
SELECT DATEADD(dd,CAST(5-GETDATE() AS int)%7,GETDATE()+7)
To verify the formula:
WITH test AS (
SELECT GETDATE() AS d UNION ALL
SELECT DATEADD(dd,1,d)
FROM test WHERE d < GETDATE() + 30
)
SELECT
d AS [input],
DATEADD(dd,CAST(5-d AS int)%7,d+7) AS [output]
FROM test
To tweak the the formula, adjust the 5- and the +7

Using SQL DateAdd algorithm, excluding weekends

I need to write a simple query that returns three weekdays prior to a given date. I don't want to create a calendar table. Is there an algorithm that uses dateadd() and datepart() that i can use to get this result?
This is something I used before as a template that I found very useful:
DECLARE #DateOld datetime, #DateNew datetimeSET #DateOld = '10-Sep-2005'SET #DateNew = GETDATE()
SET DATEFIRST 1
SELECT DATEDIFF (day, #DateOld, #DateNew) - (2 * DATEDIFF(week, #DateOld, #DateNew)) - CASE WHEN DATEPART(weekday, #DateOld + ##DATEFIRST) = 1 THEN 1 ELSE 0 END - CASE WHEN DATEPART(weekday, #DateNew + ##DATEFIRST) = 1 THEN 1 ELSE 0 END
Source: http://sqlcode.blogspot.com/2007/07/calculate-number-of-business-days.html
I ended up using a while loop to count the number of weekdays.
i keep cycling back one day at a time until i get the the desired number of weekdays using this weekday logic:
set #isweekday=case when (DATEPART(dw, #tempdate) + ##DATEFIRST) % 7 NOT IN (0, 1) then 1 else 0 end

Can't understand this query

declare #date varchar(30) = '2013-04-18'
DECLARE #WeekOfMonth TINYINT
SET #WeekOfMonth =
(
DAY(#DATE) +
(DATEPART(dw,
DATEADD (MONTH,
DATEDIFF (MONTH,
0,
#DATE),
0))
- 1) -1) / 7 + 1
print #WeekOfMonth
This is a query I found over the internet to find out week number of the month like it's '2013-03-04' today and this is second week of this month, Query is working fine, But I can't understand it and the person who has posted it over that blog haven't described it's working either. Can someone please help me to understand it better.
It's calculating the week number of the month, by adding the day number to the weekday number of the first day of that month, then divide by 7 and add 1. For example, with '2013-03-04', the day number is 4, the week number of '2013-03-01' is 6 (Friday), so the result is (4 + 6 - 1 - 1)/7 + 1 = 2.
Working from the inside out:
(DAY('2013-03-04') + (DATEPART(dw, DATEADD(MONTH, DATEDIFF(MONTH, 0, '2013-03-04'), 0)) - 1) - 1) / 7 + 1
Number of months from 1900-01-01, 1358
(DAY('2013-03-04') + (DATEPART(dw, DATEADD(MONTH, 1358, 0)) - 1) - 1) / 7 + 1
The date that is 1358 months from 1900-01-01, 2013-03-01
(DAY('2013-03-04') + (DATEPART(dw, '2013-03-01') - 1) - 1) / 7 + 1
Day of week of '2013-03-01', 6 (Friday)
(DAY('2013-03-04') + (6 - 1) - 1) / 7 + 1
The day part of '2013-03-04', 4
(4 + (6 - 1) - 1) / 7 + 1
-1 to convert Sunday = day 1 to Monday = day 1
(4 + 5 - 1) / 7 + 1
-1 because '2013-03-04' is 3 days from '2013-03-01'
= 2
Here is another way of looking at this:
You can run these statements to break it down yourself:
select datediff(month, 0, getdate()); -- Get Months since 1900-01-01
select DATEADD (MONTH, DATEDIFF (MONTH, 0, getdate()),0); -- Add Months back to 1900-01-01 to get 1st of Month (essentially stripping time and days)
select DATEPART(dw,DATEADD (MONTH, DATEDIFF (MONTH, 0, getdate()),0)-1); Get Day of Week Number for 1st of Current Month
select (day(getdate()) + DATEPART(dw,DATEADD (MONTH, DATEDIFF (MONTH, 0, getdate()),0)-1)-1); -- Add Day Number of Month for Current Date then subtract 1 to make it days, since we started on 1st
select (day(getdate()) + DATEPART(dw,DATEADD (MONTH, DATEDIFF (MONTH, 0, getdate()),0)-1)-1)/7; -- Determine how many whole weeks can be divided into this result
select (day(getdate()) + (DATEPART(dw,DATEADD (MONTH, DATEDIFF (MONTH, 0, getdate()),0))-1)-1)/7+1; -- We're zero indexed (meaning results would be zero in 1st week), so add 1 to get week number