I'm trying to select rows where a timestamp field, recdate, has a date value up to and inclusive of the last completed day of the month. For example, as this is July 2016, I want all rows with date values up to and inclusive of 31-06-2016. This used to work fine in T-SQL, I'd use the following and assign it to #today and chuck that in my WHERE:
DECLARE #today DATETIME SELECT #today = CONVERT(VARCHAR(25),DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())-0,0)));
I'm struggling in BigQuery though, I can't get DATEDIFF or GETDATE to work, was wondering if anybody had thoughts on this?
best wishes
Dave
Another way with Standard SQL.
First day current month:
SELECT DATE_TRUNC(CURRENT_DATE(), MONTH)
Last day previous month (first day current minus 1):
SELECT DATE_SUB(DATE_TRUNC(CURRENT_DATE(), MONTH), INTERVAL 1 DAY)
First day next month:
SELECT DATE_TRUNC(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), MONTH)
Last day current month (first day next month minus 1):
SELECT DATE_SUB(DATE_TRUNC(DATE_ADD(CURRENT_DATE(), INTERVAL 1 MONTH), MONTH), INTERVAL 1 DAY)
October 2020 Update (BigQuery Standard SQL)
BigQuery now support LAST_DAY function as well as arithmetic operations + and '-' for dates
So, now you can use below options to get last day of previous month
#standardSQL
select
date_trunc(current_date(), month) - 1,
last_day(date_sub(current_date(), interval 1 month)),
date_sub(last_day(current_date()), interval 1 month)
with output (having in mind it is October 14 today)
me personally - i love the first option as least verbose and straightforward!
-- ~~~~~~~~~~~~~~~~~~~
Use below as an example (BigQuery Legacy SQL)
SELECT DATE(DATE_ADD(CURRENT_DATE() , -DAY(CURRENT_DATE()), "DAY"))
BTW, there are 30 days in June :o) - with exception of Priestley's "The Thirty-First of June"
Works in standard SQL
SELECT DATE_ADD(CURRENT_DATE(), INTERVAL -EXTRACT(DAY FROM CURRENT_DATE()) DAY)
DATE_ADD( CURRENT_DATE(), INTERVAL -EXTRACT( DAY FROM CURRENT_DATE()) DAY)
That is the correct syntax for Google BigQuery.
Begining SQL 2012 there is a EOMONTH Function :
https://msdn.microsoft.com/en-us/library/hh213020.aspx
Usage:
DECLARE #date VARCHAR(255) = '07/01/2016';
SELECT EOMONTH ( #date ) AS Result;
GO
Will return 07/31/2016
DECLARE #date VARCHAR(255) = GetDate() ; -- To Get End of month for Current Month
SELECT EOMONTH ( #date ) AS Result;
GO
Will return 07/31/2016
My Bad .. I did not realize the OP was looking for last day of previous month
But this should work:
DECLARE #date Datetime = '12/31/2017' -- Input Date. Has to be Datetime NOT varchar. If incomming date is a varchar it needs to be converted to Datetime.
Select DAY( #date ) -- Returns 31
SELECT #date - DAY( #date ) as LastDayOfPrevMonth
Output:
LastDayOfPrevMonth
2017-11-30 00:00:00.000
I have tried it for most of the Edge cases like leap day , first/last day of any month etc.
Works with any version of SQL Server
SELECT convert(varchar(10),
DATEADD(mm, -1,
DATEADD(s,-1,
DATEADD(mm,
DATEDIFF(m,0,getdate())+1
,0)
)
), 103) AS [LastMonthEnd]
Related
I have two date columns, which takes into account only working days. A_date and E_date.
E_date is calculated adding +2 days to A_date, because that's the request
The problem is that if the day of A_date is 30th or 31st of the month, then E_date date needs to be the last day of the current month, and not the first or second working day of the next month.
i have tried eomonth function but that does not work because it would need a explicit date.
Do you have any idea how to solve it?
You can use EOMONTH() in SQLServer to get the last day of the month.
Example:
EOMONTH(A_date)
SELECT CASE WHEN dateadd(month,1+datediff(month,0,A_date),-1)< DATEADD(day, 2, A_date) THEN dateadd(month,1+datediff(month,0,A_date),-1) ELSE DATEADD(day, 2, A_date) END E_date
FOR input of 2019/09/30 output is 2019-09-30 00:00:00.000
I'm not sure what your question is. What I've understood so far is that you want the last date of the month in case when adding two days to A_Date jumps to the next month.
Why don't you use CASE WHEN and compare out the months, this way :
DECLARE #A_Date date = '2019/09/30';
DECLARE #A_Date_Month int = 0;
DECLARE #E_Date_Month int = 0;
SELECT #A_Date_Month = Month(Cast(#A_Date AS datetime));
SELECT #E_Date_Month = Month(DATEADD(day, 2, #A_Date));
SELECT CASE
WHEN #A_Date_Month = #E_Date_Month
THEN DATEADD(day, 2, #A_Date)
ELSE EOMONTH(#A_Date) END AS OUTPUTValue
Try out the above set and do let me know if it resolves your issue!
How to get from a date column the last date of the previous month?
It depends on your RDBMS, so let's take the opportunity to make a generic answer:
In Oracle:
LAST_DAY(ADD_MONTHS(mydate ,-1))
In MySQL:
LAST_DAY(mydate - INTERVAL 1 MONTH)
In SQL Server:
DATEADD(MONTH, DATEDIFF(MONTH, -1, mydate )-1, -1)
-- or simply:
EOMONTH(DATEADD(Month, -1, mydate ))
In Postgres:
date_trunc('month', now())::mydate - 1
have two date columns, which takes into account only working days. A_date and E_date. E_date is calculated adding +2 days to A_date, because that's the request
I would simply do:
(case when dateadd(day, 2, a_date) < eomonth(a_date)
then dateadd(day, 2, a_date)
else eomonth(a_date)
end) as e_date
If you truly want this only on the 30th or 31st of any given month and not the last 2 days of any month (since obviously not every month has 31 days) --
select A_date
,case when day(A_date) >= 30
then eomonth(A_date)
else dateadd("dd",2,A_date)
end as E_date
Other answers work for "last 2 days of any month".
How to get the current month end date through db2 query.
I should not need to modify the query for every month
Every month the sql is executing so it need to automatically take care
In Db2 11.1 this could be a solution:
select next_month(current date) - 1 day from sysibm.sysdummy1
Next_Month will return the first day of the next month from the data provided.
SELECT LAST_DAY(CURRENT_DATE) AS LASTDAY
FROM SYSIBM.SYSDUMMY1;
The query is working
LASTDAY
2019-04-30
The old way would be
CURRENT DATE - (DAY(CURRENT DATE)) DAYS + 1 MONTH
To get the last day of the current month, use this:
SELECT DATEADD (dd, -1, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0))
This will format the date for you
SELECT CONVERT(VARCHAR(10), DATE, 12)
See this for more information regarding the '12'. 12 is the right code
Another solution is to use TIMESTAMP_FORMAT as such:
TIMESTAMP_FORMAT('190404', 'YYMMDD')
I want to calculate the number of days per-quarter if start date and finish dates are given.
for example, one table has two columns, start date and finish date.
start date = 1st september and finish is 14th november.
I want to calculate the number of days present in between these two days that are present in each quarter
Q3 - 30 days
Q4 - 45 days (for this scenario)
Regards.
declare #StartDate date='2012-09-01';
declare #EndDate date='2012-11-14';
select CEILING(month(dateadd(q,datediff(q,0,dateadd(dd,number ,#StartDate)),0))/3.0) as QuarterNo,
COUNT(*) as 'number of days'
from master..spt_values
where type='p'
and dateadd(dd,number ,#StartDate)<=#EndDate
group by dateadd(q,datediff(q,0,dateadd(dd,number ,#StartDate)),0)
SQL fiddle demo
You can use a recursive query to get this. This generates the list of dates between your start and end date and then gets the count of days per quarter:
;with cte (start, enddate) as
(
select startdate, enddate
from yourtable
union all
select dateadd(dd, 1, start), enddate
from cte
where dateadd(dd, 1, start) <= enddate
)
select datepart(q, start) Quarter, count(datepart(q, start)) NoDays
from cte
group by datepart(q, start)
See SQL Fiddle with Demo
i have to get the last day of the current month. how can i get
SQLite (sqlite3)
Compute the last day of the current month.
SELECT date('now','start of month','+1 month','-1 day');
checkout this link as well if your using sqlite3
sqlite datetime functions
set dateformat dmy
select dateadd(d, -1, dateadd(m, 1, '01-' + convert(varchar, month(getdate())) + '-' + convert(varchar, year(getdate()))))
add one month to the first of this month, minus one day.
SQLITE QUERY FOR CALCULATE
NUMBER OF DAY IN A CURRENT MONTH
select strftime('%d',datetime('now','start of month','+1 month','-1 second'));
An alternative: add a month to the date, then subtract the resulting day value of the new month:
select day(dateAdd(d, -day(dateAdd(m,1,'2012-01-31')), dateAdd(m, 1, '2012-01-31')))
Oracle
SELECT LAST_DAY(SYSDATE) AS Last_day_of_month FROM DUAL;
SQL Server
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) AS Last_day_of_month
Specifically MSSQL 2005.
Here's a solution that gives you the last second of the current month. You can extract the date part or modify it to return just the day. I tested this on SQL Server 2005.
select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );
To understand how it works we have to look at the dateadd() and datediff() functions.
DATEADD(datepart, number, date)
DATEDIFF(datepart, startdate, enddate)
If you run just the most inner call to datediff(), you get the current month number since timestamp 0.
select datediff(m, 0, getdate() );
1327
The next part adds that number of months plus 1 to the 0 timestamp, giving you the starting point of the next calendar month.
select dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 );
2010-09-01 00:00:00.000
Finally, the outer dateadd() just subtracts one second from the beginning timestamp of next month, giving you the last second of the current month.
select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );
2010-08-31 23:59:59.000
This old answer (below) has a bug where it doesn't work on the last day of a month that has more days than the next month. I'm leaving it here as a warning to others.
Add one month to the current date, and then subtract the value returned by the DAY function applied to the current date using the functions DAY and DATEADD.
dateadd(day, -day(getdate()), dateadd(month, 1, getdate()))
SELECT DATEADD(M, DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP), '1990-01-31T00:00:00.000')
Explanation:
General approach: use temporal functionality.
SELECT '1990-01-01T00:00:00.000', '1990-01-31T00:00:00.000'
These are DATETIME literals, being the first time granule on the first day and last day respectively of the same 31-day month. Which month is chosen is entirely arbitrary.
SELECT DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP)
This is the difference in whole months between the first day of the reference month and the current timestamp. Let's call this #calc.
SELECT DATEADD(M, #calc, '1990-01-31T00:00:00.000')
This adds #calc month granules to the last day of the reference month, the result of which is the current timestamp 'rounded' to the last day of its month. Q.E. D.
Try this:
DATEADD (DAY, -1, DATEADD (MONTH, DATEDIFF (MONTH, 0, CURRENT_TIMESTAMP) + 1, 0)
They key points are if you can get first day of current month,Last Day of Last Month and Last Day of Current Month.
Below is the Step by Step way to write query:
In SQL Server Date Starts from 1901/01/01( Date 0) and up to now each month can be identified by a number. Month 12 is first month of 1902 means January. Month 1200 is January of 2001. Similarly each day can be assigned by unique number e.g Date 0 is 1901/01/01. Date 31 is 1901/02/01 as January of 1901 starts from 0.
To find out First day of Current Month(Current Date or a given date)
First we need to check how many months have passed since date 0(1901/01/01).
SELECT DATEDIFF(MM,0,GETDATE())
Add same number of month to date 0(1901/01/01)
SELECT DATEADD(MM, DATEDIFF(MM,0,GETDATE()),0)
Then we will get first day of current month(Current Date or a given date)
To get Last Day of Last Month
We need to subtract a second from first day of current month
SELECT DATEADD(SS,-1,DATEADD(MM, DATEDIFF(MM,0,GETDATE()),0))
To get Last Day of Current Month
To get first day of current month first we checked how many months have been passed since date 0(1901/01/01). If we add another month with the total months since date 0 and then add total months with date 0, we will get first day of next month.
SELECT DATEADD(MM, DATEDIFF(MM,0,GETDATE())+1,0)
If we get first day of next month then to get last day of current month, all we need to subtract a second.
SELECT DATEADD(SS,-1,DATEADD(MM, DATEDIFF(MM,0,GETDATE())+1,0))
Hope that would help.
Using SQL2005, you do not have access to a helpful function EOMONTH(), So you must calculate this yourself.
This simple function will works similar to EOMONTH
CREATE FUNCTION dbo.endofmonth(#date DATETIME= NULL)
RETURNS DATETIME
BEGIN
RETURN DATEADD(DD, -1, DATEADD(MM, +1, DATEADD(DD, 1 - DATEPART(DD, ISNULL(#date,GETDATE())), ISNULL(#date,GETDATE()))))
END
Query to perform:
SELECT dbo.endofmonth(DEFAULT) --Current month-end date
SELECT dbo.endofmonth('02/25/2012') --User-defined month-end date
Some links to possible answers:
http://www.extremeexperts.com/sql/Tips/DateTrick.aspx
http://www.devx.com/tips/Tip/14405
http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/
http://www.sqlservercurry.com/2008/03/find-last-day-of-month-in-sql-server.html
DECLARE
#Now datetime,
#Today datetime,
#ThisMonth datetime,
#NextMonth datetime,
#LastDayThisMonth datetime
SET #Now = getdate()
SET #Today = DateAdd(dd, DateDiff(dd, 0, #Now), 0)
SET #ThisMonth = DateAdd(mm, DateDiff(mm, 0, #Now), 0)
SET #NextMonth = DateAdd(mm, 1, #ThisMonth)
SET #LastDayThisMonth = DateAdd(dd, -1, #NextMonth)
Sometimes you really do need the last day of this month, but frequently what you really want is to describe the time interval of this month. This is the best way to describe the time interval of this month:
WHERE #ThisMonth <= someDate and someDate < #NextMonth
For completeness, in Oracle you'd do something like ...
select add_months(trunc(sysdate,'MM'),1) ...
or
select last_day(sysdate)+1 ...
DATEADD(dd, -1, DATEADD(mm, +1, DATEADD(dd, 1 - DATEPART(dd, #myDate), #myDate)))