Select data from today until the last 15th of month? - sql

I want to select a range of data from today until the last 15th (so this month or last month). How would this be done in TSQL?
Following Get last Friday's Date unless today is Friday using T-SQL it seems like I would have to make use of DATEDIFF at the least.
I'm considering building a date string, like:
set #date='yyyy-mm-15'
But yyyy or mm would not be able to be simply the current year/month, in case it has to look back a month/year.

This should give you what you want
SELECT *
FROM YourTable
WHERE YourDate > CAST((
CASE
WHEN DAY(getdate()) < 15
THEN (CAST(YEAR(GETDATE()) AS CHAR(4)) + CAST(MONTH(dateadd(month, - 1, getdate())) AS CHAR(2)) + '15')
ELSE CAST(YEAR(GETDATE()) AS CHAR(4)) + CAST(MONTH(GETDATE()) AS CHAR(2)) + '15'
END
) AS DATETIME)
EDIT
changed WHEN DAY(getdate()) > 15 to WHEN DAY(getdate()) < 15, as the results were inverted :)

Format the current date in the format yyyy-mm-15, convert back to date, compare to the current date and if this is later that today, subtract 1 month.
That's what I'd do in ANSI SQL... But apparently, MS SQL Server doesn't know "interval". Well, you can make use of DateAdd instead:
DateAdd() - Returns a new datetime value based on adding an interval to the specified date.
Where first parameter specifies on which part of the date to return a new value: yy(yyyy) for Year, mm(m) for Month, dd(d) for Day etc.
For example: select dateadd(d,2,getdate()) - adds 2 days to current date and returns new date.

Related

<Resolved> Fetch last date of a month and last minute of that day

I need to get last day of the month with time like
2023-01-31 23:59:59:000000
I'm able to get only the last day of the month with time stamp as
2023-01-31 00:00:00:000000
As jarlh said your best method is to add a day to the end of the month, then subtract a second (although if you really want the absolute maximum time I think you'd want to subtract 3 milliseconds).
EOMONTH -> Add 1 day -> Cast as datetime -> remove 1 second / 3 milliseconds. You have to cast as datetime because the EOMONTH function implicitly casts to a date
The code will be something like this:
SELECT DATEADD(SECOND, -1, CAST(DATEADD(DAY, 1, EOMONTH(#currentDate)) AS DATETIME))
SELECT DATEADD(MILLISECOND, -3, CAST(DATEADD(DAY, 1, EOMONTH(#currentDate)) AS DATETIME))
There are already similar questions with a lot of answers. You should find your anwer for sure:
Get the last day of the month in SQL
SQL query to display end date of current month
DECLARE #currentDate DATE = GETDATE()
SELECT EOMONTH (#currentDate) AS CurrentMonthED
SQL query to display end date of Next month
DECLARE #currentDate DATE = GETDATE()
SELECT EOMONTH (#currentDate, 1 ) AS NextMonthED

Calculate dates by giving a default day of month using SQL Server 2008

I need to calculate a future date by subtracting a date from another date. The catch is the date field I am subtracting has many days of the month...i.e. 10/27/2020 or 11/30/2020. What I need to do is, no matter what the day of the month is, I need to subtract the month as if it were the first day of the month no matter what it may be.
So for example I have a date 12/31/2020 I need to subtract another date 10/23/2020 from that date but I need to default 10/23/2020 to 10/01/2020 and same for any other date I would subtract from the original date. Any ideas?
You can get first day of the month and then use datediff to get the date difference.
DECLARE #table table(fromdate date,todate date)
insert into #table
VALUES ('2020-10-27','2020-12-31')
SELECT datediff(day, DATEADD(month, DATEDIFF(month, 0, fromdate), 0),todate) AS DifferenceDays
from #table
+----------------+
| DifferenceDays |
+----------------+
| 91 |
+----------------+
Not really sure what you are really asking. But I'm assuming that you want to get the date gap or difference between 2 dates. But, before that, you want to set a default day for the first date.
You can set up the first date to have day 1, then use DATEDIFF to know the gap / difference.
-- source date
declare #date date = '10/27/2020'
declare #dateSubtract date = '10/23/2020'
-- break the date, take month and year only
declare #month int = DATEPART(MONTH, #date)
declare #year int = DATEPART(YEAR, #date)
-- reconstruct the date with default day=1
select #date = CAST((STR(#month) + '/01/' + STR(#year)) as date)
-- get the calculation
select DATEDIFF(DAY, #date, #dateSubtract)
The result will be (in Days),
22
You can change the DATEDIFF parameter to MONTH or YEAR.
#UPDATE 1:
As mentioned by Alex in comment below, you can reconstruct the date using DATEFROMPARTS which more safer. Because casting from string may causing a confusion of date format.

Where datetime between 12 am of column time and 10 am next day of column time

I have a column with data type as datetime and the way data is imported is always the previous day to today.
There is not historical data stored in the table - the previous data is deleted before the new data is imported.
That being said I will like to have a where clause written where my ESTEndTime column is between 00:00:00 of the timestamp column and 10:00:00 the next day of the timestamp column.
I've searched but couldn't find anything specific to what I was looking for.
The purpose is to primarily capture the end times of those who work overnight. When the data is exported it always exported as the previous day to the next day, for example October 1 to October 2. This will allow us to see the latest logout times of those who worked overnight. In the example that I just mentioned the data will include everything from 00:00:00 October 1 to 23:59:59 October 2. There is no way for us to limit to a specific time. So using the example when I was hoping to achieve is limit it in a where clause where the time is between 00:00:00 October 1 and 10:00:00 October 2. The problem is I don't want to use those actual dates as my dates are always changing hence why I am here for some help.
Code that I have but not getting the expected results
SELECT timestamp, emp_id, dept, ESTStartTime, ESTEndTime
,CONCAT(emp_id, '-', FORMAT(ESTStartTime, 'yyyy/MM/dd-HH:mm')) AS Index2Start
,CONCAT(emp_id, '-', FORMAT(ESTEndTime, 'yyyy/MM/dd-HH:mm')) AS Index3Stop
,CONCAT(emp_id, '-', FORMAT(ESTEndTime, 'yyyy/MM/dd')) AS Index3StopDay
FROM dbo.[test]
WHERE ESTEndTime BETWEEN DATEADD(DAY, DATEDIFF(DAY, 0, timestamp), 0) + '00:00'
AND DATEADD(DAY, DATEDIFF(DAY, 1, timestamp), 1) + '10:00'
ORDER BY ESTEndTime DESC
Here is another possible way you can try
SELECT DISTINCT ee.*
FROM table ee
CROSS APPLY (
select MIN(timestamp) AS timestamp, NextDate = DATEADD(HOUR,10,DATEADD(DAY,1,MIN(timestamp))) from table
) maxdate
WHERE ee.ESTEndTime BETWEEN maxdate.timestamp AND maxdate.NextDate
See if this will work for you. I declared 2 variables to hold the previous day's date and time and the current day's date and time. I used GETDATE() to get the current date and time. I extracted the date part out of it and subtracted a day for the previous date. Then I converted the date to a VARCHAR and added the time. SQL Server will implicitly convert the string back to a DATETIME value.
--Previous day at 12:00am
DECLARE #prevday DATETIME = CONVERT(VARCHAR,CONVERT(DATE,(DATEADD(DD,-1,GETDATE())))) + ' 12:00AM';
--Current day at 10:00am
DECLARE #currentday DATETIME = CONVERT(VARCHAR,CONVERT(DATE,GETDATE())) + ' 10:00 AM' ;
SELECT timestamp, emp_id, dept, ESTStartTime, ESTEndTime
,CONCAT(emp_id, '-', FORMAT(ESTStartTime, 'yyyy/MM/dd-HH:mm')) AS Index2Start
,CONCAT(emp_id, '-', FORMAT(ESTEndTime, 'yyyy/MM/dd-HH:mm')) AS Index3Stop
,CONCAT(emp_id, '-', FORMAT(ESTEndTime, 'yyyy/MM/dd')) AS Index3StopDay
FROM dbo.[test]
WHERE ESTEndTime BETWEEN #prevday AND #currentday
ORDER BY ESTEndTime DESC

Grouping by Week Datepart, display the spanning dates e.g. "25/12/2015 - 31/12/2015"

When using Datepart to group by week, is it possible to easily have it display the dates the weeks span. Below is an example of my sql:
SELECT
'Week ' + cast(datepart(wk, Table.ApplicationDate) AS VARCHAR(2)) Week
,year(Table.ApplicationDate) Year
,COUNT(Table.Value) AS [Applications]
FROM Table
GROUP BY datepart(wk, Table.ApplicationDate), year(GrantDetail.ApplicationDate)
Ideally I'd like to have Week 2 - 25/12/2015 - 31/12/2015
This will return the date ranges you are looking for. Note that using Min and Max only works if there are reliably entries for every possible day.
select 'Week ' + cast(datepart(wk, Table.ApplicationDate) as varchar (2))
+ ' - '
+ convert(varchar(8), dateadd(wk, datepart(wk, Table.ApplicationDate) - 1, '1-1-' + cast(datepart(YEAR, Table.ApplicationDate) as varchar)), 3)
+ ' - '
+ convert(varchar(8), dateadd(wk, datepart(wk, Table.ApplicationDate), '1-1-' + cast(datepart(YEAR, Table.ApplicationDate) as varchar)) - 1, 3)
You take January 1 of the year in question, then add the number of weeks (minus 1) you've calculated to that date to get the beginning of the week. Then add one more week, minus one day, to get the end of the week.
Edit: noticed you are using DD/MM rather than MM/DD, so edited my code to convert to the correct format.
If you can assume that all your dates are covered within the data then you can use min and max, otherwise you'll need to calculate them:
dateadd(dd, -datepart(dw, min(ApplicationDate)) + 1) as StartOfWeek,
dateadd(dd, -datepart(dw, min(ApplicationDate)) + 7) as EndOfWeek
I'm assuming the your datefirst settings corresponds to the logical week you want to use as you're already relying on that. Also double-check the documentation for datepart(wk, ...) to confirm it does what you're expecting especially for dates around the beginning and end of the year. (See the accepted answer at Difficulties comprehending ISO_week and week in Microsoft SQL, what's happening exactly?)
Some people prefer to avoid the old datepart codes so here are the equivalents:
dateadd(day, -datepart(weekday, min(ApplicationDate)) + 1) as StartOfWeek,
dateadd(day, -datepart(weekday, min(ApplicationDate)) + 7) as EndOfWeek
You may find it better to group on a count of the number of weeks since a fixed reference point. January 1, 2012 happened to be a Sunday so I'll use it. All of the same logic above will still work and it doesn't really matter if any of your data falls before that date since the value of the expression will just be a negative number:
group by datediff(wk, '20120101', ApplicationDate)

DATEDIFF Getting the previous month

I want to get the previous month relative to the current date
SELECT datediff(mm,-1,2-2-2011)
This query gives 67 which is a wrong value .. where i went wrong ?
You can use DATEADD
eg.
SELECT DATEADD(month, -1, GETDATE())
This 2-2-2011 is not a valid date literal - you are subtracting 2 from 2 and then 2011 from the result - proper date literals are '2-2-2011' and #2-2-2011#. You can use GETDATE() to get the current date, instead of relying on a literal.
Nor should you be using DATEDIFF - it gives you the difference between dates.
You should be using DATEADD to calculate new dates.
Try this:
SELECT DATEADD(mm,-1, GETDATE())
This will get the date a month ago.
If you just want the month, you need to also use DATEPART:
SELECT DATEPART(mm, SELECT DATEADD(mm,-1, GETDATE()))
SELECT datepart(mm, dateadd(mm,-1,'2011/1/1') )
If you want the month before the current month, you want
SELECT MONTH(DATEADD(mm, -1, GETDATE()))
If you want the date for a month before the current date, you want
SELECT DATEADD(mm, -1, GETDATE())
BTW, SELECT datediff(mm,-1,2-2-2011) computes the number of months between day -1 and day -2011, which is 67 (2010 / 30). That's nowhere near what you seem to actually want.
You need to use DATEADD - not DATEDIFF
DATEDIFF calculates the difference between two dates - it doesn't add day or months to an existing date....
Also, you need to put your dates into single quotes: use '2-2-2011' instead of simply 2-2-2011.
And lastly: I would strongly recommend using the ISO-8601 date format YYYYMMDD (here: 20110202) - it will work regardless of the language and regional settings on your SQL Server - your date format will BREAK on many servers due to language settings.
DATEDIFF calculates the difference between your stating and ending dates
every date previous to the current date has a positive number and every date next to the current date has negative number, this works in geting your specific date weather it a day,month,year or hour to understand this better below is the syntax of datediff
DATEDIFF (your datetime type, your starting date,your ending date)
the function does (your ending date)-(your starting date)
in your case the below datediff will work just pefectly
SELECT DATEDIFF (month,[you_date_or_datetime_column],GETDATE()) = 1
You can use DATEADD try this code
For previous month
SELECT DATEADD(month, -1, GETDATE())
For 7 day previous
$date = date('Y-m-d',strtotime("-7 days"));
SELECT * FROM users WHERE `date` LIKE '%$date%'
$date varibale get previous date date