Get week number from a list of dates in SQL - sql

I'm trying to get listed the corresponding week number from the dates that result from this query.
select Date,Time,EndDate,EndTime
FROM Test
WHERE (StartDate >= '01.01.2019')
ORDER BY StartDate
Basically, I want adding to the end column the week number from this query.
I can't edit the database in anyway, I just want to extract the week number from the dates and have it as a column at the end of my results.
Sample data below:

Just use datepart function:
select datepart(week, Date), Date,Time,EndDate,EndTime
FROM Test
WHERE (StartDate >= '01.01.2019')
ORDER BY StartDate

use datepart(wk,date):-
select Date,Time,EndDate,EndTime,datepart(wk,date)as week
FROM Test
WHERE (StartDate >= '01.01.2019')
ORDER BY StartDate

In UK ISO week is used: the first year's week is the one including 4th of Jan.
So:
set datefirst 1 --this sets Monday as first day of the week
set dateformat dmy -- nosrmal date format
select Date,Time,EndDate,EndTime,datepart(iso_week,date)as week
FROM Test
WHERE (StartDate >= '01.01.2019')
ORDER BY StartDate
Remember that first days of Jan may be 52nd or 53rd week of previous year and also last day of December may belong to first week of new year.
the check to see the week number and postponed to the yeear it belongs to is the following:
week_and_year = case when datepart(iso_week,date)>=52 and month(date)=1
then concat(year(date)-1,datepart(iso_week,date))
when datepart(iso_week,date)=1 and month(date)=12
then concat(year(date)+1,datepart(iso_week,date))
else concat(year(date),datepart(iso_week,date))
end

SELECT DATEPART(WEEK,GETDATE()-14)
SELECT DATEPART(WEEK,GETDATE()-7)
SELECT DATEPART(WEEK,GETDATE())
SELECT DATEPART(WEEK,GETDATE()+7)
SELECT DATEPART(WEEK,GETDATE()+14)

If you use Vertica, try this
date_part('ISODOW', date)
'ISODOW' - The ISO day of the week, an integer between 1 and 7 where Monday is 1.

I usually use the ROW_NUMBER() function to accomplish this:
select
Date,
Time,
EndDate,
EndTime,
ROW_NUMBER() over (partition by year(EndDate), datepart(weekday, EndDate) order by EndDate) as WeekNumInYear
FROM Test
WHERE
(StartDate >= '01.01.2019')
ORDER BY
StartDate

Related

Filter query result for every Thursday of a given month

I have a SQL table with 2 columns ID (int) and CreateDate (DateTime) type.
I want to filter all the IDs for each Thursday for a given month whether I pick Jan, Feb, March, etc...
If I understand correctly, DATEPART function might help you to do that.
you can use weekday in the first parameter which returns weekday from DateTime, if you want to compare others information DATEPART might help you compare.
SELECT *
FROM T
WHERE
DATEPART ( weekday , CreateDate ) = 5
for each Thursday for a given month
Start by filtering on the month/year date range first, to reduce the number of results and keep things sargable. Then use datePart to identify the Thursday's within the selected range.
db<>fiddle
-- Assumes SET DATEFIRST 7
SELECT *
FROM YourTable
WHERE CreateDate >= '2022-01-01'
AND CreateDate < '2022-02-01'
AND DatePart(dw, CreateDate) = 5
Note, the results of Datepart(dw) may differ depending on your ##DATEFIRST setting. A deterministic version of the query would be:
SELECT *
FROM YourTable
WHERE CreateDate >= '2022-01-01'
AND CreateDate < '2022-02-01'
AND ((DatePart(dw, CreateDate) + ##DATEFIRST-1) % 7+1) = 5

52weeks rolling with running week data

Can someone suggest me how do we consider week to start on Sunday and end on Saturday, while numbering them backwards in a 52 week rolling report like week1, week2.. week52
I want to count my current week as Week1 starting on Sunday, so even if its partial week its still week1 and last week Sunday-Saturday is week2 and so on until 52nd week last year (that would roughly be in September counting backwards). I need this as I am working on a daily report that will look for sales for current week and past 51 (full) weeks. My report should also return any week without sales '0' without skipping it.
Here is a way. Note I created the recursive CTE to populate some dates. You won't have to do this step, and real only need the YourWeekOrder = ... part.
declare #startDate date = dateadd(year,-1,getdate())
declare #endDate date = getdate()
;with cte as(
select #startDate as TheDate
union all
select dateadd(day,1,TheDate)
from cte
where TheDate < #endDate)
select
TheDate
,TheWeekOfYear = datepart(week,TheDate)
,YourWeekOrder = dense_rank() over (order by cast(datepart(year,TheDate) as char(4)) + case when len(datepart(week,TheDate)) = 1 then '0' + cast(datepart(week,TheDate) as char(2)) else cast(datepart(week,TheDate) as char(2)) end desc)
from cte
order by
TheDate
option(maxrecursion 0)
SEE IT IN ACTION HERE

SQL getdate issue with month

i need help on my little problem.
SELECT FORMAT(ServiceDate, 'dd-MM-yyy") AS ServiceDate
FROM Services
WHERE Day(ServiceDate) BETWEEN '1' AND Day(getdate() -2)
AND Month(ServiceDate) =
CASE
WHEN Day(getdate()) <=2
THEN Month(getdate() -1
ELSE Month(getdate())
END
AND Year(ServiceDate) = Year(getdate())
Now the problem is the first and the second of the Month.
The query don't use the last month. It shows the actual month.
I hope its clear what i need.
if we have the 01-06-2016 and i need minus 2, so the query must give me back to the day 30-05-2016
big THX
the output for today with this query
output query
Assuming you are using sql-server, you need to use DATEADD(Day, -2, GETDATE()) for subtracting 2 days from current date.
I think I understand the logic now:
If the current day is the 1st of the month, get all the records from the start of previous month, until 2 days before it ends.
If the current day is the 2nd of the month, get all the records from the start of the previous month until one day before it ends.
If the current day is the 3rd of the month or higher, get all the records from the beginning of the current month until 2 days ago.
Since you are using the FORMAT() function that was introduced in 2012 version, you can also use the EOMONTH() function that was introduced in the same version.
This function returns the date of the end of the month of the date it receives as an argument, and also have a useful optional second argument that specifies the numbers of months to add to the date passed to the function.
Using this function will allow you to write your query without using any functions on the ServiceDate column, thus enabling the use of any indexes defined on this column.
DECLARE #Now datetime = GETDATE()
SELECT FORMAT(ServiceDate, 'dd-MM-yyy') AS ServiceDate
FROM Services
WHERE (
DAY(#Now) <= 2
AND ServiceDate >= DATEADD(DAY, 1, EOMONTH(#Now, -2))
AND ServiceDate < DATEADD(DAY, -(DAY(#Now)-1), EOMONTH(#Now, -1))
)
OR
(
DAY(GETDATE()) > 2
AND ServiceDate >= DATEADD(DAY, 1, EOMONTH(#Now, -1))
AND ServiceDate < DATEADD(DAY, -2, #Now)
)
Compute enddate as 2 days before getdate() and select data in interval from enddate's first of month and enddate.
SELECT FORMAT(ServiceDate, 'dd-MM-yyy") AS ServiceDate
FROM Services
CROSS APPLY (SELECT enddate = DATEADD(D,-2,getdate()) x
WHERE ServiceDate BETWEEN DATEADD(MONTH,DATEDIFF(MONTH,0,x.enddate),0) AND x.enddate

Number of days in quarter, SQL Server

I want to calculate the number of days per-quarter if start date and finish dates are given.
for example, one table has two columns, start date and finish date.
start date = 1st september and finish is 14th november.
I want to calculate the number of days present in between these two days that are present in each quarter
Q3 - 30 days
Q4 - 45 days (for this scenario)
Regards.
declare #StartDate date='2012-09-01';
declare #EndDate date='2012-11-14';
select CEILING(month(dateadd(q,datediff(q,0,dateadd(dd,number ,#StartDate)),0))/3.0) as QuarterNo,
COUNT(*) as 'number of days'
from master..spt_values
where type='p'
and dateadd(dd,number ,#StartDate)<=#EndDate
group by dateadd(q,datediff(q,0,dateadd(dd,number ,#StartDate)),0)
SQL fiddle demo
You can use a recursive query to get this. This generates the list of dates between your start and end date and then gets the count of days per quarter:
;with cte (start, enddate) as
(
select startdate, enddate
from yourtable
union all
select dateadd(dd, 1, start), enddate
from cte
where dateadd(dd, 1, start) <= enddate
)
select datepart(q, start) Quarter, count(datepart(q, start)) NoDays
from cte
group by datepart(q, start)
See SQL Fiddle with Demo

How can I count and group by between two date?

For example,
the start date = '20100530' and
the end date = '20100602'
How can I write a SQL to display the below result?
month: may, 2 days
month: June, 2 days
Use a recursive CTE to generate all of the dates between the start and end, and then do a simple group and count (caution, not tested, but should be close if not exactly right):
with dates (the_date) as (
select #start_date
UNION ALL
select dateadd(dd, 1, the_date) from dates where the_date <= #end_date
)
select
datepart(mm, the_date) month,
count(*) num_days
from
dates
group by
datepart(mm, the_date)
TBH, you really need to provide more schema and information about the source data. However, given what little we know, you should be able to write:
Select DateName('month', [Date]) As Month
, Cast(DateDiff(d, #StartDate, #EndDate) As varchar(10) - 1) + ' days'
From Table
Where [Date] Between #StartDate And #EndDate
What we'd need to know to refine our solutions is exactly how 2 days is supposed to be calculated. Is it the days between the start and end date? Is it the day of the second parameter?