How to get the last month data and month to date data
Today including time info : getdate()
Today without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 0)
Tomorrow without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Beginning of current month : DATEADD(month, datediff(month, 0, getdate()), 0)
Beginning of last month : DATEADD(month, datediff(month, 0, getdate())-1, 0)
so most likely
WHERE dateColumn >= DATEADD(month, datediff(month, 0, getdate())-1, 0)
AND dateColumn < DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
SQL date scenario for getting previous month's data to-date on the 1st of month, then drop last month
WITH dates AS (SELECT * FROM VALUES ('2021-03-01'),
('2021-03-02'),
('2021-03-03'),
('2021-02-01'),
('2021-02-02') v(day))
SELECT day
,DATE_TRUNC('month',DATEADD('day',-1, day)) AS from_date
,DATEADD('month',1, from_date ) AS to_date
FROM dates
ORDER BY 1;
we get the results:
DAY FROM_DATE TO_DATE
2021-02-01 2021-01-01 00:00:00.000 2021-02-01 00:00:00.000
2021-02-02 2021-02-01 00:00:00.000 2021-03-01 00:00:00.000
2021-03-01 2021-02-01 00:00:00.000 2021-03-01 00:00:00.000
2021-03-02 2021-03-01 00:00:00.000 2021-04-01 00:00:00.000
2021-03-03 2021-03-01 00:00:00.000 2021-04-01 00:00:00.000
SQL Server query to get the data from previous month if the column value is not present in next month
This answers the original version of the question.
Assuming that month
is stored as a date with the first first day of the month, then a simple method uses recursive CTEs:
with cte as (
select restaurant, num_items, month,
dateadd(month, -1,
coalesce(lead(month) over (partition by restaurant order by month),
max(month) over ()
)
) as end_month
from t
union all
select restaurant, num_items, dateadd(month, 1, month), end_month
from cte
where month < end_month
)
select *
from cte
order by restaurant, month;
Here is a db<>fiddle.
Calculate the date of the previous month and the date before previous month using current date (data flow, ADF)
You can use subMonths function, something like:
subMonths(toDate('2020-01-01'), 1)
subMonths(toDate('2020-01-01'), 2)
Get the records of last month in SQL server
SELECT *
FROM Member
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, date_created) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
You need to check the month and year.
Related Topics
How to Use SQL Server Stored Procedures in Microsoft Powerbi
How to Do Many to Many Table Outer Joins
Maximum Length of an SQL Query
Oracle SQL Group by "Not a Group by Expression" Help
How to Perform a SQL 'Not In' Query Faster
Create View Using Linked Server Db in SQL Server
Difference Between on and Where Clauses in SQL Table Joins
Sql Query to Find The Duplicate Records
Sql - Filtering Large Tables with Joins - Best Practices
Order by Month and Year in SQL with Sum
Sqlite Insert Taking Long Time
How to Substitute a Left Join in Sql
How to Get The SQL String from a JPA Query Object