last day of the current month? - sql

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

Related

Get first day of yyyyMM format

I wish to get the first and the last day of the month with
select CONVERT(varchar,dateadd(d,-1,dateadd(m,1,cast(cast('201812' as varchar(6))+'01' as date))),112)
Actually I can get the last day of month but I don't know how can I get the first day of month.
If you are starting with '201801asyyyymm`, then use:
select convert(date, yyyymm + '01') as first_day_of_month,
eomonth(convert(date, yyyymm + '01')) as last_day_of_month

Query select where date between "1st day of current month" and "current day"

I need to select data from SQL Server database between the 1st day of the current month and current day.
SELECT *
FROM table_name
WHERE date BETWEEN "1st day of current month" AND "current day"
You can make use of EOMONTH() to jump to the last day of the month, of the previous month. Then, just add 1 day, by using DATEADD() with 1 as the increment for the day, to get the 1st day of the current month.
SELECT *
FROM <table>
WHERE <date> BETWEEN DATEADD(DAY, 1, EOMONTH(GETDATE(), -1)) and GETDATE()
I think this should work,
SELECT *
FROM TABLE_NAME
WHERE date BETWEEN DATEADD(mm, DATEDIFF(mm,0,date), 0) AND GETDATE()
May this will help you,
select * from TABLE_NAME
where date between
dateadd (DAY, -(datepart (DAY, getdate ())) + 1, convert (date, GETDATE ()))
and
convert (date, getdate ())
I don't recommend using between for this purpose. I prefer to have code that works on both dates and datetimes without modification.
In addition, SQL Server has the convenient datefromparts() function. So, I recomend:
WHERE date >= DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) AND
date < CONVERT(DATE, DATEADD(DAY, 1, GETDATE()))

Is there is a way to get the month end date for every 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')

The last day of the previous month - BigQuery

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]

How do I calculate the last day of the month in SQL?

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)))