Getting week number of date in SQL - sql

Is there a way to get the week number of a date with SQL that is database independent?
For example to get the month of a date I use:
SELECT EXTRACT(MONTH FROM :DATE)
But the EXTRACT function doesn't know about weeks in SQL92.
Please pay attention to the fact that I want a solution that is database independent! Do not misinterpret this as a question regarding MS SQL Server.

There doesn't appear to be a single standard SQL function to extract the week number from a date - see here for a comparison of how different SQL dialects can extract different dateparts from date fields.

You can try this.
declare #date datetime
select #date='2013-03-15 00:00:00'
select 'Week No: '+ convert(varchar(10),datepart(wk,#date)) as weekno

Try this one :
SELECT DATENAME(yy,GETDATE())+RIGHT(DATENAME(wk,GETDATE()),2)
To understand DATENAME, please follow this link : sqltutorials.blogspot.be/2007/05/sql-datename.html and for the right, suite101.com/article/sql-functions-leftrightsubstrlengthcharindex-a209089 . There are examples to better understand ;-) It will work on MS and other sql servers normally ;-)

The only db independent solution I see is to get the number of days between today and Jan 1 of curr. year. Then divide it by 7 and round it up. There is 73 days from Jan 1 till today, which gives 10.43 as week number. The ISO week number is 11.
Correction: the number of days between last day of the current week and Jan 1 of curr. year. In this case the ISO week is 10, and 68/7 = 10 (rounded).

The best idea I found is
SELECT ROUND(((DAY(NOW())-1)/7)+1)

select (DATEPART(yyyy , CAST(GETDATE() AS datetime)) * 100 +
DATEPART(ww , CAST(GETDATE() AS datetime))) as week

Related

Select records when month and day are less than current date

I am using SQL Server Mgmt Studio. I need to create a formula that will only select records when the month and day of a date/time field, LAW_TAEEMASTER.MASTR_ENTRY, is less than or equal to the current month and day. For example, If LAW_TAEEMASTER.MASTR_ENTRY = 8/20/2015 and current date = 7/6/2017, exclude. If LAW_TAEEMASTER.MASTR_ENTRY = 12/21/2014 and current date = 1/15/2017, include. Date formatting is my weakness. Here is what I have tried:
select LAW_TAEEMASTER.MASTR_ENTRY
from LAW_TAEEMASTER
WHERE day(LAW_TAEEMASTER.MASTR_ENTRY) <= DAY(GETDATE()) and MONTH(LAW_TAEEMASTER.MASTR_ENTRY) <= MONTH(getdate())
and
select LAW_TAEEMASTER.MASTR_ENTRY
from LAW_TAEEMASTER
WHERE AND DATEPART(DAY,LAW_TAEEMASTER.MASTR_ENTRY) <= DATEPART(DAY,GETDATE()) AND DATEPART(MONTH,LAW_TAEEMASTER.MASTR_ENTRY) <= DATEPART(MONTH,GETDATE())
but these just evaluate the month and day separately and as a number, greater than or less than, so it's excluding records. How can I get SQL to recognize these as part of a date and just ignore the year?
I would do this using month() and day():
where month(LAW_TAEEMASTER.MASTR_ENTRY) * 100 + day(LAW_TAEEMASTER.MASTR_ENTRY) < month(getdate()) * 100 + day(getdate())
If performance is an issue, I would recommend a computed column with an index.
Explain the logic and code:
Use CONVERT(varchar(5),<your_date> ,110)). The 110 arguement means USA standard time and have an ouput like mm-dd-yyyy. Then we only take the first five character which is the month and day of the date.
110 = mm-dd-yyyy
read more about cast and convert here
my sample table:
MASTER_ENTRY
2017-08-30
2017-07-05
2017-07-04
Then I executed this query
SELECT LAW_TAEEMASTER.MASTR_ENTRY
FROM LAW_TAEEMASTER
WHERE CONVERT(varchar(5),LAW_TAEEMASTER.MASTR_ENTRY ,110) <= CONVERT(varchar(5),GETDATE() ,110)
result:where month and day equal or earlier current month and day
MASTER_ENTRY
2017-07-05
2017-07-04
I hope this helps and welcome to StackOverflow. If you find this answer or any other answer solves your problem please mark it as the solution. This will help the community and fellow programmers who run into the same problem in the future. Thanks.

Datepart Week Sql (With 53 weeks for year)

I'm calculating the week for a specific date in SQL for example
'2016-01-20' (yyyy-mm-dd) but SQL returns week: 4, and that is wrong because this year the first week started on '2016-01-04' the result must be week: 3.
I think the issue is generatad because 2015 was a year with 53 weeks, any solution to that? Thank you and I'm sorry for my bad English
In tSQL the DATEPART() is returning the correct data based on US and Most of Europe as well as UK See here
You can use SET DATEFIRST to adjust the start position however.
The ISO 8601 definition for week 01 is the week with the year's first Thursday in it. I am using Intersystems cache which apparently does not account for that either. So I have used this to address that
CASE WHEN 7-datepart(dw,dateadd(dd,1,dateadd(yy,datediff(yy,0,getdate())-1,0))) < 2
THEN datepart(wk,getdate())-1 ELSE datepart(wk,getdate()) END as WeekNum

Teradata Change format of Week Number

I'm pretty new to SQL so I hope this isn't a dumb question, tried to google but couldn't find anything.
I'm summing sales of departments per week in SQL and am using TD_SYSFNLIB.WEEKNUMBER_OF_YEAR (trans_dt) to get the week number.
I think everything is working except I'd like to change the format of the weeks to the start date of the week, e.g. week 1 = 1/4/15
Also, i'm not sure how to handle the very first of the year week 0 since I think that should be grouped up with week 52 of last year.
The following date math trick should get you Beginning of Week as an actual date without having to join to the SYS_CALENDAR view or using a function:
SELECT CURRENT_DATE - ((CURRENT_DATE - DATE '0001-01-07) MOD 7) AS BOW;
Starting with TD14 there's NEXT_DAY which returns the following weekday, if you subtract 7 days you get the previous day:
next_day(trans_dt - 7, 'sunday')

return week number based on date

I am new to T-SQL and needed urgent assistance here.
I am trying to get the week number from a given date.
I understand that there is a build in function for it but the value return is not exactly what I wanted.
For e.g., by using select datepart(wk, '2013-01-07'), it would return me '2'.. but the actually fact is it should return '1' instead of '2'.
Any ideas how to correct this issue?
You can use dy datepart specifier to get dayOfYear number and divide it by 7:
select (datepart(dy, '2013-01-05') - 1) / 7 + 1;
Working DEMO.
Try this
SELECT DATEPART(WEEK,GETDATE())
This depends on hop you define the first week. Does it always start on the same weekday? or does it always start on the first of January? If you want it to always start on the same weekday, then use Set datefirst to tell T-SQL what weekdaty you want to define as the start of the week. If you want it to always start on Jan 1, then just use day of year instead of week, subtract 1, integer divide by 7 and add 1.
declare #dat DateTime = getdate()
Select Select (datepart(dy, #dat)-1) / 7 + 1
Although going from memory, I believe the ISO standard for the first week of the year is the week in the year that the first Thursday of the year is in. This would possibly explain why the built in function gives a result different to that you require.

What is happening in this query?

I am trying to get the last of month, and in order to that i have written the following, to calculate the no. of days between today and the last date.
select datediff(DAY,GETDATE(),dateadd(m,1,getdate()))-GETDATE()
the bold part gives me the no. of days between today and a month from today, say 30 or 31. and then I am subtracting today's date from 30 or 31, which is " -getdate() "
The output for the above query is
1786-06-06 11:44:30.540
Could you please explain what is happening in the query? I am not looking for a solution, I would like to know how is SQL-Server interpreting the query.
Thanks. :)
The bold part of the expressions does not return a date, it returns a number of days:
31
Convert that to a datetime:
SELECT CONVERT(DATETIME, 31);
This is 31 days after day 0 (1900-01-01):
1900-02-01
Now, subtract GETDATE() as an integer (41512 days after day 0):
SELECT 31 - 41512 = -41481
Now add -41481 days to day 0:
SELECT DATEADD(DAY, -41481, 0);
-- or
SELECT DATEADD(DAY, -41481, '19000101');
Or:
SELECT CONVERT(DATETIME, 31 - CONVERT(INT, GETDATE()));
Now, I strongly recommend a couple of things:
Don't use implicit date math. #date_var_or_col - 1 for example fails with new data types like DATE and DATETIME2.
Don't use shorthand like m. If you mean MONTH, just take the massive productivity hit and type out MONTH. To see why, tell me if this provides the results you expect:
SELECT DATEPART(y, GETDATE()), DATEPART(w, GETDATE());
I am subtracting today's date from 30 or 31, which is " -getdate() "
Sounds like you understand exactly what is happening, but maybe don't understand the results.
You are implicitly converting GETDATE() to a number, which represents the number of days (and fractional days) since 1/1/1900 12:00:00 AM
When you "subtract" GETDATE() (41,511 as of 8/27/2013) from 30 or 31 you get an answer of -41,480, or 41,480 days before 1/1/1900, which would be about 6/6/1786 (plus or minus a few hours for the fractional part).