SQL Get interval last week (sunday to saturday) - sql

I need a simple sql script where i can grab the rows with a date between sunday 2 weeks ago and saturday the previous week.
I need the query to return the elements no matter what day of this week I run the query.
Lets say I run the query today: Thursday 12. dec 2016. (12-08-2016)
I need to get this interval:
SELECT * FROM table WHERE date BETWEEN '11-27-2016' AND '12-03-2016'

DECLARE #StartInterval DATE,
#EndInterval DATE,
#Today = GETDATE()
SET #EndInterval = DATEADD(dd,-1,DATEADD(dd,-1*(DATEPART(dw,#Today)-1),#Today))
SET #StartInterval = DATEADD(dd,-6,#EndInterval)
SELECT *
FROM table
WHERE date BETWEEN #StartInterval AND #EndInterval

You can use:
select * from table where date between next_day(date, 'SUN')-21 AND
next_day(date, 'SAT')-14

Related

How to get the last seven days of one month's data in SQL?

I used below SQL to get last day of the month, but I need last seven days of the month:
DECLARE #dt as DATETIME = '7/29/2018'
DECLARE #LastDayOfTheMonth as DATETIME = DATEADD(DAY, -1, DATEADD(Month, 1, DATEADD(DAY,1 - DAY(#dt),#dt)))
SELECT #LastDayOfTheMonth
I could also use this SQL function in order to get above result, but I need last 7 days of any month's records.
SELECT EOMONTH('7/29/2018')
Just use DATEADD again to take 1 to 6 more days off #LastDayOfTheMonth.
SELECT #LastDayOfTheMonth, DATEADD(DAY,-1,#LastDayOfTheMonth), ..
If you want to return 7 values from a function, suggest making it a table function.

How to change day of date in SQL server and set last day of month if the day does not exist in the month

I tried using this
dateadd(month, 0, dateadd(day,(30-datepart(dd,'2015-02-28')),'2015-02-28'))
to get the required output and instead of getting '2015-02-28' i get '2015-03-02'. How is it possible to change day of date in SQL and set last day of month if the day does not exist in the month ?
====Update with sample data =============
Note: Goal is not to get the last day of the month
If i want to change the day to 30 and if it's a month which has only 28 days. it should be the end of the month date. If not date should be 30th.
Changing the day to 30th
If Feb it should be - '2015-02-28'
If march it should be - '2015-03-30'
If April it should be - '2015-04-30'
There exists a function for this if your sql server version is 2012 or higher:
SELECT EOMONTH('2015-02-15')
returns 2015-02-28
-- Replace Day portion of #OrigDate with #NewDay.
-- If the result would be beyond the end of the month, return the last day of the month
create function ReplaceDay ( #OrigDate date, #NewDay int )
returns date
as
begin
declare #NewDate date
-- Deal with extreme cases, in case someone passes #NewDay = 7777 or #NewDay = -7777
if #NewDay < 1
set #NewDay = 1
if #NewDay > 31
set #NewDay = 31
-- Subtract the DAY part of the original date from the new day.
-- Add that many days to the original date
-- Example: if the original date is 2018-02-08 and you want to replace 08 with 17, then add 17-08=9 days
set #NewDate = DateAdd ( d, #NewDay-Day(#OrigDate), #OrigDate )
-- Have we ended up in the next month?
-- If so subtract days so that we end up back in the original month.
-- The number of days to subtract is just the Day portion of the new date.
-- Example, if the result is 2018-03-02, then subtract 2 days
if Month(#NewDate)<>Month(#OrigDate)
set #NewDate = DateAdd ( d, -Day(#NewDate), #NewDate )
return #NewDate
end
go
select dbo.ReplaceDay ( '2017-02-08', 17 ) -- Returns 2017-02-17
select dbo.ReplaceDay ( '2017-02-08', 30 ) -- Returns 2017-02-28
for sql server 2012 or higher versions please check HoneyBadger's answer.
for older versions:
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#mydate)+1,0))

Create date of a specific weekday two weeks before the current week

I'm trying to create a SQL statement (in H2 Dialect) that creates a DATE which is
the tuesday in the "week-of-year" that is two weeks from the current week.
For example, given CURRENT_DATE() returns 2014-04-23, the date that I want would be 2014-04-08, which is the Tuesday in the week that is two weeks before the week the Date "2014-04-23" is in.
How can I express this with H2's Date and Time functions?
In sql-server I would do it like this
DECLARE #date DATE = GETDATE();
SELECT DATEADD(DAY,3-DATEPART(WEEKDAY,#date),DATEADD(WEEK,-2,#date))
Where '3' represents day of the week (Tuesday) and '-2' represents subtracting two weeks.
So now in h2 it is very similar
SELECT DATEADD('DAY',3-DAY_OF_WEEK(CURRENT_DATE()),DATEADD('WEEK',-2,CURRENT_DATE()))

Get 1st Day of Week (Sunday)

I have this formula in my column to calculate the start date of a given week :
dateadd(week,[Week]-(1),
dateadd(day,(-1),
dateadd(week,
datediff(week,(0),
CONVERT([varchar](4),[Year],(0))+'-01-01'),
(1))))
Where Week and Year are other fields like 38 and 2012
Problem is, it calculates the start date of week 38/2012 as a monday (17th Sept), I would like it to be a sunday instead (16th Sept) is this possible?
Many thanks.
This will return you the first day of the week, given a week number and a year, assuming that the first day of the week is a Sunday.
Standard exclusions apply, e.g. don't try year 1499.
declare #tbl table ([Week] int, [Year] int)
insert #tbl select 38,2012
union all select 1,2012
union all select 0,2012
union all select 1,2013
select DATEADD(
Week,
[Week]-1,
DATEADD(
Day,
(8-##datefirst)-DATEPART(dw, CAST([Year]*10000+101 AS VARCHAR(8))),
CAST([Year]*10000+101 AS VARCHAR(8))))
from #TBL
Result
2012-09-16 00:00:00.000
2012-01-01 00:00:00.000
2011-12-25 00:00:00.000
2012-12-30 00:00:00.000
Note that the Week number starts from 1, and if the week doesn't start on a Sunday, then the first day of that week could end up in an earlier year (row #4). Because the Weeks are relative, you can use Week 0, -1 etc and it will still give you a result (row #3), rightly or wrongly.
You may also notice I used a different method to create a date out of the year, just as an alternative.
The (8-##datefirst) portion of the query makes it robust regardless of your DATEFIRST setting.
If you want the first day of the week to be Sunday you could change your database to make it so, using the DATEFIRST setting.
function getFirstDateOfThisWeek(d)
{
var TempDate = new Date(d || new Date());
TempDate.setDate(TempDate.getDate() + (#Config.WeekStartOn - 1 - TempDate.getDay() - 7) % 7);
return TempDate;
}
var StartDate = getFirstDateOfThisWeek(new Date()); //1st date of this week

calculate week number within a date range

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