How will I calculate week number within a date range ? Here my week starts from Saturday to Friday. And I have a start date and end date. With this, how will i calculate using SQL Query ?
Use DATEPART to get the Week number,
and DATEFIRST to set the first day of the week. (See http://msdn.microsoft.com/en-us/library/ms181598.aspx)
Example to get all week numbers in range with Saturday as the first day of week.
SET DATEFIRST 6
SELECT DISTINCT
DATEPART(WEEK, createDate)
FROM
tblUser
WHERE
createDate > '2005-01-01' AND createDate < '2011-01-01'
ORDER BY
DATEPART(WEEK, createDate)
You can use this and your SQL work operates well:
SET LANGUAGE us_english -- with your language
GO
Related
I have two event tables with timestamped data: Registered, Signed_In.
Both have rows such as: original_timestamp, user_id
I am trying to find out users who haven't signed in within 30 days after registering. I have used the following query but I cannot add a WHERE clause to it.
I tried a query but I am getting hourly difference, whereas I wanted days difference which is unsupported in BigQuery.
SELECT Signed_In.user_id, TIMESTAMP_DIFF(Registered.original_timestamp, Signed_In.original_timestamp, HOUR) AS days_difference
FROM `test_db.Signed_In` signed_in
JOIN `test_db.Registered` registered
ON Signed_In.user_id = Registered.user_id
GROUP BY 1,2
ORDER BY 2 DESC
WHERE days_difference > '30'
I am getting two columns: user_id, days_difference but the days_difference shows hours and my WHERE clause is rejected when I use it.
You can try this below code-
Note: Using Ordinal Position for GROUP BY and ORDER BY is not a good practice. Its always safe and standard to use the column names directly.
SELECT Signed_In.user_id,
TIMESTAMP_DIFF(Registered.original_timestamp, Signed_In.original_timestamp, HOUR) AS days_difference
FROM `test_db.Signed_In` signed_in
JOIN `test_db.Registered` registered
ON Signed_In.user_id = Registered.user_id
WHERE DATE_DIFF(Registered.original_timestamp, Signed_In.original_timestamp, Day) > '30'
GROUP BY 1,2
ORDER BY 2 DESC
Just replace HOUR to DAY in your query:
SELECT Signed_In.user_id, TIMESTAMP_DIFF(Registered.original_timestamp, Signed_In.original_timestamp, DAY) AS days_difference
Correct values are:
MICROSECOND
MILLISECOND
SECOND
MINUTE
HOUR
DAYOFWEEK
DAY
DAYOFYEAR
WEEK: Returns the week number of the date in the range [0, 53]. Weeks begin with Sunday, and dates prior to the first Sunday of the year are in week 0.
WEEK(<WEEKDAY>): Returns the week number of timestamp_expression in the range [0, 53]. Weeks begin on WEEKDAY. datetimes prior to the first WEEKDAY of the year are in week 0. Valid values for WEEKDAY are SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.
ISOWEEK: Returns the ISO 8601 week number of the datetime_expression. ISOWEEKs begin on Monday. Return values are in the range [1, 53]. The first ISOWEEK of each ISO year begins on the Monday before the first Thursday of the Gregorian calendar year.
MONTH
QUARTER
YEAR
ISOYEAR: Returns the ISO 8601 week-numbering year, which is the Gregorian calendar year containing the Thursday of the week to which date_expression belongs.
DATE
DATETIME
TIME
I am trying to get last weeknumber when week is first week of the year (e.g. current date is 1/1/2017)
Below query works for all other week except the first week of the year.
However below query returns nothing for the first week of the year.
where DateDim_Date.YEAR=year(DATEADD(Day, -7, getDate()))
and DateDim_Date.WEEKNUMBER = datePart(wk,getDate())-1
Thanks in advance!
Use this:
where DateDim_Date.YEAR=year(DATEADD(MONTH, -1, getDate()))
and DateDim_Date.WEEKNUMBER = datePart(wk,DATEADD(DAY,-7,GETDATE()))
You want to get (weeknumber of (current date - 7 days)), not (weeknumber of current date) -1
I'm trying to create custom week numbers and ranges based on user entered Week Start Day.
I'm passing that User defined day with SET Datefirst = #Userdefinedvalue (using a function to map my weekday start values to T-SQL's). Also I have a function to gets me the last day of the current week.
What is the best approach for this?
My Goal is: if I select Tuesday as my start day of the week the Stored Procedure to generate my week numbers and start/end dates based on my selection for the entire year
The idea is to find the first day of the week. First, use SQL Server built in functions to move the start of the week to the Sunday (in the US) by subtracting datepart(wd). Actually datepart(wd) returns values form 1 to 7 and we want them 0 to 6.
Then, add back in an offset based on your date of the week. Here is example code:
declare #offset int (case when #DateFirst = 'Mon' then 1
when #DateFirst = 'Tue' then 2
...
when #DateFirst = 'Sun' then 0
end);
select dateadd(dd, #offset - (datepart(wd, thedate) - 1)
thedate) as WeekStartDate
I'm using SQL SERVER 2005 and have a table which stores challans datewise. It has a field 'Quantity'
I want to have a sum of Quantity for the weeks of the month. But these weeks have to start from Tuesday To Monday (this is an international standard for Oil Accounting)
You can use set DATEFIRST to set the first day of the week, and then use datepart.
These SQL Statements should get you what you want. Assumption is that your table is called and the date column is
SET DATEFIRST 2;
select datepart(week, :my_date), sum(quantity)
from
group by datepart(week, :my_date)
I want to calculate Last Week Number of Month in SQL. I am having Week Number and Year.
Eg. If I pass WeekNo=51 , Year=2008 , than function should return LastWeekofMonth= 52.
I want to calculate Week number using below standards.
According to ISO 8601:1988 that is used in Sweden the first week of the year is the first week that has at least four days within the new year.
So if your week starts on a Monday the first Thursday any year is within the first week. You can DateAdd or DateDiff from that.
Please Help me..........
Thanks in advance.
SELECT WEEK(LAST_DAY(STR_TO_DATE('2008-51-Mon', '%x-%v-%a')));
Should do the trick for getting the last week number of month with MySQL :
I first convert to a date, then I get the last day of the month (here: 2008-12-31), then I compute the week of the last day of the month (52).
It should be easy to turn it into a function.
Hope this helps.
This is fairly straightforward if you use a calendar table. The month you need is given by this query.
select iso_year, month_of_year
from calendar c
where iso_year = 2008 and iso_week = 51
group by iso_year, month_of_year
--
iso_year month_of_year
2008 12
So you can use that result in a join on the calendar table, like this.
select max(c.iso_week) as last_week_of_month
from calendar c
inner join
(select iso_year, month_of_year
from calendar c
where iso_year = 2008 and iso_week = 51
group by iso_year, month_of_year) m
on m.iso_year = c.iso_year and m.month_of_year = c.month_of_year;
--
last_week_of_month
52
Here's one example of a calendar table, but it's pretty thin on CHECK constraints.
If you're using SQL Server, you can perform a calculation by using a master table, without creating a calendar table. This fellow gives you a very good explanation, which I recommend that you read. His SQL for calculating the first and last Sundays of each month can be adapted for your use:
declare #year int
set #year =2011
select min(dates) as first_sunday,max(dates) as last_sunday from
(
select dateadd(day,number-1,DATEADD(year,#year-1900,0))
as dates from master..spt_values
where type='p' and number between 1 and
DATEDIFF(day,DATEADD(year,#year-1900,0),DATEADD(year,#year-1900+1,0))
) as t
where DATENAME(weekday,dates)='sunday'
group by DATEADD(month,datediff(month,0,dates),0)
Edit: Once you have the date of the Thursday, you can get the week number from that date like this:
DECLARE #Dt datetime
SELECT #Dt='02-21-2008'
SELECT DATEPART( wk, #Dt)