T-SQL select date withing 30 days range - sql-server

I would like to select all the rows with dates between 30 days range from today,
so between 22-04-2022 till 22-05-2022,
I've tried
SELECT DATEXP, ID FROM TABLE
where DATEXP > cast(getdate() + 30 as date) and DATEXP <= cast(getdate() as date)
but this doesn't seem to do it

You should use the DATEADD() function here:
SELECT DATEXP, ID
FROM yourTable
WHERE DATEXP >= GETDATE() AND DATEXP < DATEADD(day, 30, GETDATE());
Also note that your inequality was incorrect. You should have the earlier date on the left GTE comparison and the later date on the right LT comparison.

Your condition seems to be wrong, you are expecting the date to be >= Today + 30 days BUT less than today.
So if for example.
Today is 22 April 2022
Today + 30 = 22 May 2022
If I have a date DATEXP say 23 May 2022, it can't be >= 22 May 2022 and LESS then 22 April 2022 at the same time.
Maybe you want the Condition to be >= Today AND < Today + 30?

Related

How to find the past 4 weeks of the same weekday value starting today

I am trying to select records from today and the same day of each week for the last 4 weeks.
Today (Tuesday)
Last Tuesday
The Tuesday before that
The Tuesday before that
I need this to be tied to current date because I am going to run this query every day so I don't want to use a between or something where I manually specify the date range.
Everything I have found or tried so far has pulled the last month of data but not the last 4 weeks of the same weekday.
select *
from table
where thedatecolumn >= DATEADD(mm, -1, GETDATE())
This works but pulls everything from the last month.
If today's date is 7/10/2019 I need
Data from 7/10/2019
Data from 7/3/2019
Data from 6/26/2019
Data from 6/19/2019
Every day I will run this query, so I need it to be dynamic based on the current date.
I believe you want to look back 21 days and then filter those dates that have the same day of week:
select * from table
where thedatecolumn >= DATEADD(DAY, -21, CAST(GETDATE() AS DATE))
and DATEPART(WEEKDAY, thedatecolumn) = DATEPART(WEEKDAY, GETDATE())
You Can try using a recursive cte which starts today and repeatedly substracts 7 days - so you ensure you always land on the same weekday. Following an example:
WITH cteFromToday AS(
SELECT 0 AS WeeksBack, GETDATE() AS MyDate
UNION ALL
SELECT WeeksBack + 1 AS WeeksBack, DATEADD(d, -7, MyDate) AS MyDate
FROM cteFromToday
)
SELECT TOP 5 *
FROM cteFromToday
OPTION ( MaxRecursion 0 );
This is quite simple. Substitute CURRENT_TIMESTAMP here for any given date.
SELECT CONVERT(DATE,CURRENT_TIMESTAMP) AS Today,
DATEADD(DAY,-7,CONVERT(DATE,CURRENT_TIMESTAMP)) AS LastWeek ,
DATEADD(DAY,-14,CONVERT(DATE,CURRENT_TIMESTAMP)) AS TwoWeeksAgo,
DATEADD(DAY,-21,CONVERT(DATE,CURRENT_TIMESTAMP)) AS ThreeWeeksAgo
SO, if you want to get data for a set of ranges for one entire day with those dates:
SELECT something
WHERE
datetimecolumn >= CONVERT(DATE,CURRENT_TIMESTAMP) AND datetimecolumn < DATEADD(DAY,1, CONVERT(DATE,CURRENT_TIMESTAMP)) -- Todays range,
OR datetimecolumn >= DATEADD(DAY,-7,CONVERT(DATE,CURRENT_TIMESTAMP)) AND datetimecolumn < DATEADD(DAY,1,DATEADD(DAY,-7,CONVERT(DATE,CURRENT_TIMESTAMP)))-- LastWeek ,
OR datetimecolumn >= DATEADD(DAY,-14,CONVERT(DATE,CURRENT_TIMESTAMP)) AND datetimecolumn < DATEADD(DAY,1,DATEADD(DAY,-14,CONVERT(DATE,CURRENT_TIMESTAMP)))-- TwoWeeksAgo,
OR datetimecolumn >= DATEADD(DAY,-21,CONVERT(DATE,CURRENT_TIMESTAMP)) AND datetimecolumn < DATEADD(DAY,1, DATEADD(DAY,-21,CONVERT(DATE,CURRENT_TIMESTAMP))) -- ThreeWeeksAgo

SQL DATEADD(weekday, 1, date) does not seem to work?

Here is my query:
SELECT ID AS 'securityid'
, date
, DATEADD(DW, 1, adate) AS 'lagged_date_v2'
, DATEADD(DAY, 1, adate) AS 'lagged_date_v1'
, aclose AS 'previous_close'
FROM mytable
WHERE adate BETWEEN '20170101 09:00' AND '20170630 18:00' AND
ID = 100056;
Here are the output from the code above:
I compared the results to DATEADDby day and by weekday and it returns the same results.
Column adate is just typical date, we can tell Jan 28, 2017 is Saturday. However, on this row, both lagged_date_v1 and lagged_date_v2 return Jan 28. If I use DATEADD by weekday correctly, I should see Jan 30 instead Jan 28, right?
My sql server version is 2008.
If I use DATEADD by weekday correctly, I should see Jan 30 instead Jan
28, right?
Wrong. In SQL Server, weekday doesn't mean days that aren't weekend days. It means which day of the week (1-7) is the day in question based on the current datefirst setting.

yearweek on SQL server

How can I extract the year and week combination from a date in SQL Server using T-SQL and have it match the MySQL yearweek result?
For example these MySQL queries (Click here for MySQL SQL Fiddle):
SELECT yearweek('2013-12-31');
SELECT yearweek('2014-01-01');
This returns 201352 for both dates. That is the expected result.
But in SQL Server...
datepart works as expected for the year extract
sometimes datepart does not return the expected value for iso_week
The MySQL result cannot be achieved with this T-SQL query...
SELECT datepart(year, #dt) * 100 + datepart (iso_week, #dt);
T-SQL versions of the MySQL queries above (Click here for T-SQL SQL Fiddle):
SELECT datepart(year, '2013-12-31') * 100 + datepart (iso_week, '2013-12-31');
SELECT datepart(year, '2014-01-01') * 100 + datepart (iso_week, '2014-01-01');
The result is 201352 for the first date and 201401 for the second date.
However, this is not the expected result because...
2014-01-01 belongs to the last week of 2013
So the expected result is 201352
Do any of you more experienced T-SQL developers know how to extract the year/week of a given date and have this match what I see in MySQL?
I need to have the week start on Monday. This is why I am using iso_week. I have tested the results with week anyway and found the same issue. This query also produces 201401 when 201352 is expected.
SELECT datepart(year, '2014-01-01') * 100 + datepart (week, '2014-01-01');
If you look at the ISO_Week datepart definition at http://msdn.microsoft.com/en-us/library/ms174420.aspx, you'll see the following:
ISO 8601 includes the ISO week-date system, a numbering system for
weeks. Each week is associated with the year in which Thursday
occurs...
The numbering system in different countries/regions might not comply
with the ISO standard.
Since January 1, 2014 was a Wednesday; January 2, 2014 was the first Thursday of the year and thus week 1 of 2014 (according to ISO 8601).
Furthermore, looking at the MySQL definitions for yearweek and week, there are several mode options (http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week)
So, I think you're going to have to write your own yearweek function for the week counting rule you want:
CREATE FUNCTION dbo.yearweek(#date date)
RETURNS INT
as
begin
set #date = dateadd(dd,-datepart(dw,#date)+1, #date)
return datepart(year,#date)*100 + datepart(week,#date)
end
go
select dbo.yearweek('2013-12-31'), dbo.yearweek('2014-01-01')
NOTE: I haven't fully tested this code, and I'm not sure exactly what your requirements are. This is just meant as an example of the type of process you need to follow.
I think it's because you're using "ISO_WEEK" as the datepart
Look at the description under the "ISO_WEEK datepart" here: http://msdn.microsoft.com/en-us/library/ms174420.aspx
using "WEEK" instead might get the desired result
TO extract YEAR, MONTH or DAY you can simply use the YEAR, MONTH and DAY function as shown in the followinf example. for any other part you have to use the DATEPART function , read here for a detailed list of arguements you can pass to DATEPART function.
SELECT YEAR(GETDATE()) AS [YEAR]
, DATEPART(WEEK, GETDATE()) [Week]
UPDATE
SELECT CAST(YEAR(GETDATE()) AS VARCHAR(4)) +'-'
+ CAST(DATEPART(WEEK, GETDATE()) AS VARCHAR(2))
It seems to me that what you want is a week number based on the previous Monday. Is this correct? If so, iso_week is no use to you as it is based on this week's Thursday.
To get the year and week based on the previous Monday, I think you need something like the following.
set datefirst 1 ;
select
SomeDate ,
datename( weekday, SomeDate ) as [WeekdayName] ,
datepart( weekday, SomeDate ) as [Weekday] ,
datepart( week, SomeDate ) as [Week] ,
datepart( iso_week, SomeDate ) as [ISO_week] ,
dateadd( day, -( datepart( weekday, SomeDate ) - 1 ), SomeDate ) as [PreviousMonday] ,
datepart( year, dateadd( day, -( datepart( weekday, SomeDate ) - 1 ), SomeDate ) ) as [MondayYear] ,
datepart( week, dateadd( day, -( datepart( weekday, SomeDate ) - 1 ), SomeDate ) ) as [MondayWeek]
from
dbo.DateDemo
order by
SomeDate ;
Abbreviated sample output is as follows.
SomeDate PreviousMonday MondayYear MondayWeek
2013-12-25 2013-12-23 2013 52
2013-12-26 2013-12-23 2013 52
2013-12-27 2013-12-23 2013 52
2013-12-28 2013-12-23 2013 52
2013-12-29 2013-12-23 2013 52
2013-12-30 2013-12-30 2013 53
2013-12-31 2013-12-30 2013 53
2014-01-01 2013-12-30 2013 53
2014-01-02 2013-12-30 2013 53
2014-01-03 2013-12-30 2013 53
2014-01-04 2013-12-30 2013 53
2014-01-05 2013-12-30 2013 53
2014-01-06 2014-01-06 2014 2

TSQL Logic in SSRS

I am building a report which has the header field as PropertyStatementForHalfyear Ending :<Date>
So in the DATE field I need to put either May 28 or Nov 28 depending on the date the report Runs
Whats The logic I need to write ??
For example if I run the report today i.e. June 22, I need to display PropertyStatementForHalfyear Ending : 28 Nov 2013
if I run it in December 2013, I need to display PropertyStatementForHalfyear Ending : 28 May 2014
You could use something like this:
DECLARE #DateThreshold1 DATE = '20130528'
DECLARE #DateThreshold2 DATE = '20131128'
DECLARE #CurrentDate DATE = '20131201'
IF #CurrentDate > #DateThreshold2
SELECT CONVERT(VARCHAR(50), DATEADD(YEAR, 1, #DateThreshold1), 106)
ELSE IF #CurrentDate > #DateThreshold1
SELECT CONVERT(VARCHAR(50), #DateThreshold2, 106)
ELSE
SELECT CONVERT(VARCHAR(50), #DateThreshold1, 106)
For dates from 20130101 through 20130528, this will return 28 May 2013
For dates from 20130529 through 20131128, this will return 28 Nov 2013
For dates past 20131128, this will return 28 May 2014
You can easily package this up into a function or a SSRS code snippet
If you're not into IF/CASE statements, like me:
with dt as
(select CAST('2013-11-28' as datetime) dt) --dt becomes your datetime column.
, ymdt as (select
DATEPART(year, dt) y,
DATEPART(month, dt) m,
DATEPART(day, dt) d,
dt
from dt) --split into year, month and date for readability
select y, m, d, dt,
DATEADD(month, 5 + d/28 - (m + d/28) % 6, --add months depending on month and day
DATEADD(day, 28 - d --go to the correct day
, dt) --start calculation from dt (the sql date functions' parameter order has always baffled me)
) HalfYearEndDate
from ymdt
The SQL engine merges all of this into one big fat constant scan or scalar expression on your datetime column.
You should create a SQL or VB function for this if you need this in other reports and also so it doesn't clutter up your queries.
Also: Don't do text formatting in T-SQL unless absolutely necessary! Return a datetime column and do it in the report itself. The format you need to set on the textbox is "dd MMM yyyy" (without the quotes when using the designer).

SQL to select records with a date greater than 40 days prior to start of month

I have a field in my table that holds a date and is in Datetime format.
I wish to select all records where the date in that field is greater than the date that is 40 days prior to the 1st of the current month.
Struggling to come up with the correct T-SQL syntax to do this.
This expression gives you the date you are looking for:
DATEADD(DAY, -DATEPART(d, GETDATE()) + 1 - 40, GETDATE())
Will this work
select #urdatecolumn > (getdate()- (DAY(getdate()) + 40-1))
Try this
where dt_blah > DATEADD(d,-40,DATEADD(wk, DATEDIFF(wk, 0, dateadd(dd, 6 - datepart(day, dt_blah), dt_blah)), 0)

Resources