How to get date range from week number in sql - sql-server-2008

I would like to get date range from week number in sql.
eg .
select datepart(week,GETDATE()) // 37
I want to get dates from week 37(4/09/2016 , 05/09/2016 , 06/09/2016 , 07/09/2016 , 08/09/2016 , 09/09/2016 , 10/09/2016)

Try this,
DECLARE #StartDate DATE = dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
, #EndDate DATE = dateadd(day, 7-datepart(dw, getdate()), CONVERT(date,getdate()))
SELECT DATEADD(DAY, nbr - 1, #StartDate) as CurrentWeekDates
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY c.object_id ) AS Nbr
FROM sys.columns c
) nbrs
WHERE nbr - 1 <= DATEDIFF(DAY, #StartDate, #EndDate)

Related

SQL select date range by month and year

How do I select date range from this query?
E.g : From Month('2017-05-22') And Year(date1) = Year('2017-05-22')
to Month('2018-05-22') And Year(date1) = Year('2018-05-22')
My current query :
SELECT
date1
FROM
data
WHERE
Month(date1) = Month('2018-05-22') And Year(date1) = Year('2018-05-22')
I'd convert those literals to dates using str_to_date:
SELECT MONTH(date1)
FROM data
WHERE date1 BETWEEN STR_TO_DATE('2017-05-22', '%Y-%m-%d') AND STR_TO_DATE('2018-05-23', '%Y-%m-%d')
Note that between is inclusive on the first argument and exclusive on the second, so I bumped the day to the 23rd.
BETWEEN condition to retrieve values within a date range.
For example:
SELECT *
FROM order_details
WHERE order_date BETWEEN CAST('2014-02-01' AS DATE) AND CAST('2014-02-28' AS DATE);
This MySQL BETWEEN condition example would return all records from the order_details table where the order_date is between Feb 1, 2014 and Feb 28, 2014 (inclusive). It would be equivalent to the following SELECT statement:
SELECT *
FROM order_details
WHERE order_date >= CAST('2014-02-01' AS DATE)
AND order_date <= CAST('2014-02-28' AS DATE);
SELECT TO_CHAR(systemts, 'yyyy-mm') as yyyymm,
max(notenum) - min(notenum) + 1 as notenum_range
FROM your_table_name
WHERE systemts >= to_date('2018-01-01', 'yyyy-mm-dd') AND
systemts < to_date('2018-07-17', 'yyyy-mm-dd')
GROUP BY TO_CHAR(systemts, 'yyyy-mm');
DECLARE #monthfrom int=null,
#yearfrom int=null,
#monthto int=null,
#yearto int=null
/**Region For Create Date on Behalf of Month & Year**/
DECLARE #FromDate DATE=NULL
DECLARE #ToDate DATE=NULL
SET #FromDate=DateAdd(day,0, DateAdd(month, #monthfrom - 1,DateAdd(Year, #yearfrom-1900, 0)))
SET #ToDate=DateAdd(day,-1, DateAdd(month, #monthto - 0,DateAdd(Year, #yearto-1900, 0)))
/**Region For Create Date on Behalf of Month & Year**/
SELECT DISTINCT month ,Year FROM tbl_Att
WHERE (DATEADD(yy, year - 1900, DATEADD(m, Month - 1, 1 - 1)) BETWEEN CONVERT(DATETIME, #FromDate, 102) AND
CONVERT(DATETIME, #ToDate, 102))

Year-Over-Year Data for last week

I am currently writing a query that will give me last weeks data (lets assume "SALES") and last years data for the same week. This is what I have to get last weeks data and it works fine:
Set DATEFIRST 1
Select DATEPArt(dd, DateAdded) AS 'Day of the Month',
count(*)AS 'Number of Users'
from TABLE1
Where DateAdded >= dateadd(day, -(datepart(dw, getdate()) + 6), CONVERT(date,getdate()))
AND DateAdded < dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
Group by DATEPArt(dd, DateAdded)
Order by 'Day of the Month'
Now I want to add another column that will give me last years data from the same week. This is what I was thinking:
Set DATEFIRST 1
Select DATEPArt(dd, DateAdded) AS 'Day of the Month',
count(*)AS 'Number of Users'
from TABLE1
Where DateAdded >= DATEADD(yy,DATEDIFF(yy,0,GETDATE())-1,0)
AND DateAdded < DATEADD(yy,DATEDIFF(yy,0,GETDATE())+1,0)
AND DateAdded >= dateadd(day, -(datepart(dw, getdate()) + 6), CONVERT(date,getdate()))
AND DateAdded < dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
Group by DATEPArt(dd, DateAdded), DateAdded
Order by 'Day of the Month'
Problem is that I am still getting last weeks numbers (this year, I need it to be last year). This leads me to believe the error has to be here somewhere:
DateAdded >= DATEADD(yy,DATEDIFF(yy,0,GETDATE())-1,0)
AND DateAdded < DATEADD(yy,DATEDIFF(yy,0,GETDATE())+1,0)
I appreciate everyone's help!!
You are looking for an OR condition
WHERE (DateAdded >= DATEADD(yy,DATEDIFF(yy,0,GETDATE())-1,0)
AND DateAdded < DATEADD(yy,DATEDIFF(yy,0,GETDATE())+1,0))
OR (DateAdded >= dateadd(day, -(datepart(dw, getdate()) + 6), CONVERT(date,getdate()))
AND DateAdded < dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate())))

How to calculate days between two dates,

Is it possible in MySQL to easily to get the number of days between two dates, group by months and then disperse those days between the months, so that when I group by month, I get to see how many days inbetween two those two dates fall into each month.
Example: creation 05.05.2014 to expiration 06.06.2014 returns 32 days. I want to display this as:
May: 26 days
June: 5 days
So far I've got:
SELECT MONTHNAME(date) as month_name,
SUM(DATEDIFF(expiration, date)) AS num_days
FROM reservations
GROUP BY month_name
But it doesn't disperse the days corretly by month, just drop them all into the group-by -start-date-month, obviously. Any ideas would be highly appriciated.
I would build a comprehensive date temp table (or CTE) first.
From there you can select what you'd like, and group it however suits your needs.
IF OBJECT_ID('TEMPDB..#Dates') IS NOT NULL DROP TABLE #Dates
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = '05/05/2014'
SET #EndDate = '06/06/2014'
;WITH Dates AS
(
SELECT CAST(CONVERT(VARCHAR(8), #StartDate,112) AS INT) AS DateId
, CAST(#StartDate AS DATE) AS Date
, CAST(#StartDate AS DATETIME) AS DateTime
, DATEPART(QUARTER, #StartDate) AS QuarterId
, 'Q' + CAST(DATEPART(QUARTER,#StartDate) AS CHAR(1)) AS Quarter
, DATEPART(MONTH, #StartDate) AS MonthId
, DATENAME(MONTH, #StartDate) AS Month
, DATEPART(DAY, #StartDate) AS Day
, DATEPART(YEAR, #StartDate) AS Year
, DATENAME(DW,#StartDate) AS DayOfWeek
, DATEPART(DAYOFYEAR, #StartDate) AS DayOfYear
UNION ALL
SELECT CAST(CONVERT(VARCHAR(8),DATEADD(DAY, 1, D.DateTime), 112) AS INT) ASDateId
, CAST(DATEADD(DAY, 1, D.DateTime) AS DATE) AS Date
, CAST(DATEADD(DAY, 1, D.DateTime) AS DATETIME) AS DateTime
, DATEPART(QUARTER,DATEADD(DAY,1,D.DateTime)) AS QuarterId
,'Q'+CAST(DATEPART(QUARTER,DATEADD(DAY, 1, D.DateTime)) AS CHAR(1)) AS Quarter
, DATEPART(MONTH,DATEADD(DAY, 1, D.DateTime)) AS MonthId
, DATENAME(MONTH,DATEADD(DAY, 1,D.DateTime)) AS Month
, DATEPART(DAY,DATEADD(DAY, 1, D.DateTime)) AS Day
, DATEPART(YEAR,DATEADD(DAY, 1, D.DateTime)) AS Year
, DATENAME(DW,DATEADD(DAY,1, D.DateTime)) AS DayOfWeek
, DATEPART(DAYOFYEAR,DATEADD(DAY,1, D.DateTime)) AS DayOfYear
FROM Dates AS D
WHERE D.DateTime < #EndDate
)
SELECT DateId AS DateId
, Date AS Date
, DateTime AS DateTime
, QuarterId AS QuarterId
, Quarter AS Quarter
, MonthId AS MonthId
, Month AS Month
, Day AS Day
, Year AS Year
, DayOfWeek AS DayOfWeek
, DayOfYear AS DayOfYear
, ROW_NUMBER() OVER(ORDER BY DateId)-1 AS DayCount
INTO #Dates
FROM Dates AS D
ORDER BY D.DateId
OPTION (MAXRECURSION 32767)
-- SELECT * FROM #Dates
SELECT COUNT(Day) AS CountOfDays, Month
FROM #Dates
GROUP BY Month

How to add hours to current date in SQL Server?

I am trying to add hours to current time like
-- NOT A VALID STATEMENT
-- SELECT GetDate(DATEADD (Day, 5, GETDATE()))
How can I get hours ahead time in SQL Server?
DATEADD (datepart , number , date )
declare #num_hours int;
set #num_hours = 5;
select dateadd(HOUR, #num_hours, getdate()) as time_added,
getdate() as curr_date
Select JoiningDate ,Dateadd (day , 30 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (month , 10 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (year , 10 , JoiningDate )
from Emp
Select DateAdd(Hour, 10 , JoiningDate )
from emp
Select dateadd (hour , 10 , getdate()), getdate()
Select dateadd (hour , 10 , joiningDate)
from Emp
Select DateAdd (Second , 120 , JoiningDate ) , JoiningDate
From EMP
The DATEADD() function adds or subtracts a specified time interval from a date.
DATEADD(datepart,number,date)
datepart(interval) can be hour, second, day, year, quarter, week etc;
number (increment int);
date(expression smalldatetime)
For example if you want to add 30 days to current date you can use something like this
select dateadd(dd, 30, getdate())
To Substract 30 days from current date
select dateadd(dd, -30, getdate())
declare #hours int = 5;
select dateadd(hour,#hours,getdate())
SELECT GETDATE() + (hours / 24.00000000000000000)
Adding to GETDATE() defaults to additional days, but it will also convert down to hours/seconds/milliseconds using decimal.
If you are using mySql or similar SQL engines then you can use the DATEADD method to add hour, date, month, year to a date.
select dateadd(hour, 5, now());
If you are using postgreSQL you can use the interval option to add values to the date.
select now() + interval '1 hour';

displaying dates of entire week starting day as saturday

I have got the code in this site for all weeks in a year as follows,i should populate week dates, starting date as saturday and end date as friday. when the week is finished it should enter to the next week with dates.
how could i achieve this please help me.
DECLARE #Year INT=2013;
DECLARE #start DATE;
--DECLARE #WK INT=2
SET #start = DATEADD(YEAR, #Year-1900, 0);
;WITH n AS
(
SELECT TOP (366) -- in case of leap year
TDate = DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, #start)
FROM sys.all_objects
),
x AS
(
SELECT md = MIN(TDate) FROM n
WHERE DATEPART(WEEKDAY, TDate) = 7 -- assuming DATEFIRST is SATURDAY
),
y(TDate,wk) AS
(
SELECT n.TDate, ((DATEPART(DAYOFYEAR,n.TDate)-
DATEDIFF(DAY, #start,x.md)-1)/7)+1
FROM n CROSS JOIN x
WHERE n.TDate >= x.md
AND n.TDate < DATEADD(YEAR, 1, #start)
)
SELECT [date] = TDate, [week] = wk
FROM y WHERE wk < 53
ORDER BY [date];
Not really sure what you're asking, but based on your query above this will give week numbers, based on Saturday being the first day of the week, for 2013:
DECLARE #Year INT=2013;
DECLARE #start DATE;
SET #start = DATEADD(YEAR, #Year-1900, 0);
SET DATEFIRST 6; -- Set start of week as Saturday
WITH n AS
(
SELECT TOP (366) -- in case of leap year
TDate = DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, #start)
FROM sys.all_objects
)
select TDate
, DATEPART(WEEK,TDate)
from n
where year(TDate) = 2013;
Edit:
So based on the various comments and answers I think what is required here is, for a given day, return all days in that same week, with Saturday as the first day of the week. So something like this:
set datefirst 6; -- make sure first day of week is Saturday
declare #date date = getdate(); -- change date as required here
with daysOfWeek as
(
select [date] = dateadd(dd, -datepart(dw, #date) + 1, #date)
union all
select [date] = dateadd(dd, 1, [date])
from daysOfWeek
where [date] < dateadd(dd, -datepart(dw, #date) + 7, #date)
)
select [date], dayOfWeek = datename(dw, [date])
from daysOfWeek
Which gives results:
I think this is what's required here?
Second edit:
First, create the function:
create function dbo.weekDates (#date date)
returns #dates table ([date] date, [dayofweek] varchar(9))
as
begin
with daysOfWeek as
(
select [date] = dateadd(dd, -datepart(dw, #date) + 1, #date)
union all
select [date] = dateadd(dd, 1, [date])
from daysOfWeek
where [date] < dateadd(dd, -datepart(dw, #date) + 7, #date)
)
insert into #dates ([date], [dayofweek])
select [date], [dayOfWeek] = datename(dw, [date])
from daysOfWeek;
return
end
go
Using the function:
set datefirst 6 -- Set Saturday as first day of week
select * from dbo.weekDates (getdate()) -- Change input parameter as required
I HAVE ACHIEVED TO DISPLAY THE WEEK DATES BUT IT IS DISPLAYING THE NEXT WEEK DATES I WANT TO DISPLAY THE CURRENT WEEK DATES, HERE START DAY IS SATURDAY AND END DAY IS FRIDAY
ALTER FUNCTION GetCurrentWeek()
RETURNS #TWeek TABLE (TWeek NVARCHAR(20))
AS
BEGIN
DECLARE #Year INT= DATEPART(YEAR,GETDATE());
DECLARE #start DATE;
SET #start = DATEADD(YEAR, #Year-1900, 0);
;WITH n AS
(
SELECT TOP (366) -- in case of leap year
TDate = DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY name)-1, #start)
FROM sys.all_objects
),
x AS
(
SELECT md = MIN(TDate) FROM n
WHERE DATEPART(WEEKDAY, TDate) = 7 -- assuming DATEFIRST is SATURDAY
),
y(TDate,wk) AS
(
SELECT n.TDate, ((DATEPART(DAYOFYEAR, n.TDate)
- DATEDIFF(DAY, #start, x.md)-1)/7) + 1
FROM n CROSS JOIN x
WHERE n.TDate >= x.md
AND n.TDate < DATEADD(YEAR, 1, #start)
)
INSERT #TWeek
SELECT [date] = TDate
FROM y WHERE wk =DATEPART(wk, GetDate())
ORDER BY [date];
RETURN;
END