Select all where date in Last month sql [duplicate] - sql

This question already has answers here:
Get the records of last month in SQL server
(23 answers)
Closed 9 years ago.
How can I get last month date like
select * from table where date in ( last month )
I dont want the last 30 days
AND how can I get last month automatically

Assuming you want all items where the date is within the last month i.e. between today and 30/31 days ago:
Select *
From Table
Where Date Between DATEADD(m, -1, GETDATE()) and GETDATE()

You can use this
Select * from table where date between #startdate and #enddate
Or
SELECT * FROM DATE_SAMPLE WHERE
DATEPART(YEAR, SAMPLE_DATE) = '2013' AND
DATEPART(MONTH,SAMPLE_DATE) = '01' AND
DATEPART(DAY, SAMPLE_DATE) = '01'
Is it usefull for you?

select * from table
where month(date)=month(getdate())-1

Edit
if you mean last month from today. or previous month from a specific date then you need to do something like this
SELECT DATEPART(MONTH, DATEADD(MONTH, -1, [Date]))
Or to get records from previous month of the year you can do something like this
SELECT * FROM Table
WHERE MONTH(Date) = DATEPART(MONTH, DATEADD(MONTH, -1, [Date]))
AND YEAR(Date) = DATEPART(YEAR, DATEADD(MONTH, -1, [Date])) --<-- or pass year for which year you are checking
To make your aquery SARGable (Suggested by t-clausen.dk)
select * from table
where date >=dateadd(m, datediff(m, 0, current_timestamp)-1, 0)
and date < dateadd(m, datediff(m, 0, current_timestamp)-1, 0)
Read here more about sargable Queries when working with date/datetime datatypes.

You can try to use the between statement to get the specific dates:
Select * from table where date between '01-01-2014' and '14-01-2014'

Related

Getting the week number as alias in sql analysis

this is my first question here. Hopefully I´m clear enough what I´m searching for.
My problem is following:
On this analysis I want to get from the last 7 weeks, the summarized prices of each week. Its working with out any problems, but now I would like to add the weeks number of each week as alias.
In my tests I was using for example something like this:
DECLARE #week7 varchar(10)
SET #week7 = DATEPART(wk, GetDate())
One of my problems is, that I´m not allowed to work with "EXEC".
This is just an example of my analysis:
SELECT DISTINCT(
SELECT SUM(Price)
FROM tblBookingdata
WHERE(Datum BETWEEN DATEADD(wk, -7, DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) AND DATEADD(wk, -6, DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))))) AS '7 weeks ago', (
SELECT SUM(Price)
FROM tblBookingdata
WHERE(Datum BETWEEN DATEADD(wk, -6, DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) AND DATEADD(wk, -5, DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))))) AS '6 weeks ago'
I would like the column name to show the week number from each sub select. That the output would be for example for this week: 40 (as column name) and 900 as price summary.
So I tried to work here with DECLARE and assign #week7 for example with the current week number. But here I got stuck, due it seems like I need to work here with EXEC.
Is this only possible with "EXEC" or are there any other solutions to solve this? I was looking in the www, but currently I´m stucking a bit. Thankful for every help! :)
I think the DateDiff function is your friend here. Are you using SQL Server? This won't display a row for the week if there are zero records in that week, but this should be close to what you want.
select WeeksAgo, sum(Price) as Price from (
select
Price
,Datediff(wk, Datum, getDate()) as WeeksAgo
,Datum --not used
from
tblBookingdata
)DataByWeek
where WeeksAgo between 0 and 7 --should this be 0-6?
group by WeeksAgo
I think you're looking for something like this. The prior 7 weeks are calculated from GETDATE based on a numbers table with 1, 2, 3, ... 7. Then the booking Prices are summarized by week where the Datum is within the prior 7 weeks. This will display NULL in price_sum if there were no sales that week.
drop table if exists #tblBookingdata;
go
create table #tblBookingdata(
Datum date not null,
Price int not null);
go
;with
weeks_cte(wk) as (
select datepart(wk, dateadd(wk, w*-1, getdate()))
from (values (1),(2),(3),(4),(5),(6),(7)) v(w)),
bookings_cte(wk, price_sum) as (
select datepart(wk, Datum), sum(Price)
from #tblBookingdata
where Datum>dateadd(wk, -7, getdate())
group by datepart(wk, Datum))
select *
from weeks_cte wc
left join bookings_cte b on wc.wk=b.wk;

SQL 15th of the month for Next Year

SQL query to get the 15 of the month for the following year.
Today
select getdate() = 2017-08-23 17:05:24.143
Looking for: 2018-8-15 00:00:00
I know how to get a year from today:
select dateadd(year,1,datediff(day,0,getdate()))
I know how to get the beginning of the month:
SELECT DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
However I am having trouble combining the two.
You can use datefromparts for SQL Server versions 2012 and above.
select datefromparts(year(getdate())+1,month(getdate()),15)
Truncate the current day to the start of the month with the code you have, but add 12 months (so, a year), and add 14 days.
select dateadd(day,14,dateadd(month, 12+datediff(month, 0, getdate()), 0))
SELECT DATEADD(month, DATEDIFF(month, 0, DATEADD(year, 1, DATEDIFF(day, 0, GETDATE())), 0)
Vamsi Prabhala's answer deserves to be accepted.
But, you should consider creating a Calendar Table because it greatly simplifies working with dates in general.
Here is a pretty simply query that yields the results that you want:
select * from Calendar C where C.year = datepart(year, getdate()) + 1
and C.day_of_month = 15 and C.month = datepart(m, getdate())
Rextester Demo

Function to go back 2 years, first day of last month

I'm hoping to find a solution for this to automate a report I have. Basically what I'm trying to accomplish here is grabbing a date (first day of previous month, two years ago through last day of previous month current year).
So the date span if running this month would look like this: between 4/1/2013 and 3/31/2015
I have found code to get the date two years ago but I'm not able to also incorporate the month functions... Any help is very much appreciated!
For year I'm using this:
SELECT CONVERT(VARCHAR(25),DATEADD(year,-2,GETDATE()),101)
First day of previous month 2 years ago:
SELECT CONVERT(DATE,dateadd(day, -1, dateadd(day, 1 - day(GETDATE()), GETDATE())))
Last day of last month:
SELECT CONVERT(DATE,DATEADD(month, DATEDIFF(month, 0, DATEADD(year,-2,GETDATE())), 0))
Then just do whatever logic you need with them
Your where clause can look something like this:
where date >= cast(dateadd(year, -2,
dateadd(month, -1, getdate() - day(getdate()) + 1)
) as date) and
date < cast(getdate() - day(getdate()) + 1 as date)
This makes use of the handy convenience that subtracting/adding a number to a datetime is the same as adding a date. The start date says: get the first day of the month, then subtract one month, then subtract two years. This could have been done as dateadd(month, -25, . . .), but I think separating the logic is clearer.
This gives you two dates you are looking for:
SELECT
CAST((DATEADD(yy, -2, DATEADD(d, -1 * DATEPART(dd, getdate()) + 1 , GETDATE() ))) as date) as yourTwoYearsAgoDate,
CAST((DATEADD(d, -1 * DATEPART(dd, GETDATE()), GETDATE())) as date) as yourEndOfLastMonthDate
Given a reference date (e.g. "today"),
declare #today date = '23 April 2015'
The 1st of the month is computed by subtracting 1 less than the day number of the current month:
select first_of_current_month = dateadd(day,1-day(#today),#today)
The last day of the previous month is day 0 of the current month, so to get the last day of the previous month, just subtract the current day number:
select last_of_previous_month = dateadd(day,-day(#today),#today)
Moving two years back is easy:
select two_years_back = dateadd(year,-2, #today )
Putting it all together, this should do you:
declare #today date = '23 April 2015'
select *
first_day_of_current_month = dateadd(day,1-day(#today),#today),
last_day_of_previous_month = dateadd(day, -day(#today),#today) ,
date_from = dateadd(year,-2, dateadd(day,1-day(#today),#today) ) ,
date_thru = dateadd(day, -day(#today),#today)
yielding the expected results:
first_day_of_current_month: 2015-04-01
last_day_of_previous_month: 2015-03-31
date_from : 2013-04-01
date_thru : 2015-03-31
So you should be able to say something like this:
select *
from foo t
where t.transaction_date between dateadd(year,-2, dateadd(day,1-day(#today),#today) )
and dateadd(day, -day(#today),#today)
If you have to deal with datetime values rather than date, its easier to not use between and say something like this:
declare #today date = current_timestamp -- get the current date without a time component
select *
from foo t
where t.transaction_date >= dateadd(year,-2, dateadd(day,1-day(#today),#today) )
and t.transaction_date < dateadd(year, 0, dateadd(day, -day(#today),#today)
[superfluous addition of 0 years added for clarity]

Select dates inside current month SQL

I have a table similar to one below. I'm trying to select only the rows where the Start Date is in the current month. Here is what I have so far, but it's not working.
SELECT *
FROM TABLE1
WHERE StartDate = MONTH(getdate())
How can I select only the values where the start date is in the current month?
Use this construct to avoid functions on the StartDate columns (like MONTH or YEAR). These functions will prevent any index or statistics being used/
SELECT *
FROM TABLE1
WHERE
StartDate >= DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
AND StartDate < DATEADD(month, 1+DATEDIFF(month, 0, GETDATE()), 0)
Any answer that puts a function on StartDate will not scale as expected. See error number 2 here. The filter is now non-sargable, and index/statistics can't be used. Every row will be looked at for a table scan.
You need to check the month of both fields
WHERE MONTH(startdate) = MONTH(getdate())

Getting the previous months data

This seems to have been answered several times for the past 30 days. But seemingly not what I need.
If, for example, today is July 10th, 2012. I'm looking to pull all of June's data. I will need to run this query several days after the start of each month
There is certainly better ways to do this, but one way would be this:
DECLARE #Date DATETIME
SET #Date = '20120710'
SELECT *
FROM YourTable
WHERE YourDateColumn >= CONVERT(VARCHAR(6),DATEADD(MONTH,-1,#Date),112)+'01'
AND YourDateColumn < CONVERT(VARCHAR(6),#Date,112)+'01')
-- first day of previous month
select DateAdd(Month, DateDiff(Month, 0, GetDate())-1,0)
-- last day of previous month
Select DateAdd(day,-1,DateAdd(Month,1,DateAdd(Month,
DateDiff(Month, 0,GETDATE())-1,0)))
Please replace GETDATE() with your date column
Ah, in that case you need something like:
SELECT *
FROM
reporting_table_name_goes_here
WHERE
DATEPART(month, YourDateColumn) = DATEPART(month, DATEADD(month, -1, getdate()))
AND DATEPART(year, YourDateColumn) = DATEPART(year, DATEADD(month, -1, getdate()))
Check out MSDN for details.