Need Last Month of Last Year Data - sql

I am trying to write a query that looks at the last month and last month of last year data to compare. So since I am writing this in August of 2022 I want to see July of 2022 and July of 2021. I know I can run a between dates and have to update it every month but I want this to feed into PowerBi and be an automated report.
I can get last month's just fine the issue is last year last month. I have tried a couple of different queries and they either error out and fail or return nothing.
I am currently skipping the part for last month as I know it works. Can I please get some help with the last year part?
Declare #StartofCurrentMonth datetime
Set #StartofCurrentMonth = dateadd(month, DATEDIFF(MONTH,0,CURRENT_TIMESTAMP),0)
Select BranchID, ItemID, CAST(Ledgerdate AS Date) As 'LedgerDate', TransactionType
From ItemLedger
Where --LedgerDate >= DateAdd(Month, -1, #StartofCurrentMonth) AND LedgerDate < #StartofCurrentMonth OR
**Ledgerdate >= DATEADD(Year, -1, #startofcurrentMonth) AND LedgerDate <** **DATEADD(Month,-12,#startofCurrentMonth)**
AND TransactionType IN ('Item.Move', 'Item.Putaway')
Order By LedgerDate
Thank you

I figured it out finally.
I changed the last year stuff to:
Ledgerdate >= DATEADD(MONTH, -13, #startofcurrentMonth) AND LedgerDate < DATEADD(Month,-12,#startofCurrentMonth))
Thank you.

Related

SQL SELECT SUM BETWEEN 1 Year from now to start ot the year

so I'm kinda stuck with a little query to get the SUM of the time period I want. So it already works but I want that it's automatically between 1 year from now and the beginning of the year.
SELECT SUM(N_EXCL), S_CUSTNO, S_CUSTNAME1, D_INVOICEDATE
from sao.INVOICE_P i
WHERE D_INVOICEDATE > DATEADD (year, -1, getdate ())
AND D_INVOICEDATE < DATEADD (month , -6 ,Getdate () )
GROUP BY S_CUSTNO, S_CUSTNAME1, D_INVOICEDATE
Currently I would have to change the query every month but I try to find a way to avoid it.
Ok. Maybe i wasn't clear enough. My problem is the -6 i have to write down. I want to switch it to a parameter that will automatically change up the date so that i get data from 01.01.2021 - 22.06.2021. So same date, but different year.
If I understand your question, you should be able to do this:
SELECT SUM(N_EXCL), S_CUSTNO, S_CUSTNAME1, D_INVOICEDATE
from sao.INVOICE_P i
WHERE D_INVOICEDATE between DATEADD(year, -1, getdate()) AND DATEFROMPARTS(getdate(), 1, 1)
GROUP BY S_CUSTNO, S_CUSTNAME1, D_INVOICEDATE
So instead of using where and I'm using where between. And I'm checking for todays date last year till 1st of January current year.
If you need from 1st of January previous year you can use:
between DATEFROMPARTS(year(getdate() -1), 1, 1) AND DATEADD(year, -1, getdate())

not getting previous month record using datepart in sybase

Using below depart syntax to fetch for previous month record, it is working fine till previous year,however it is giving 0 value in January month.How can we get pervious month with date part even if year is change ?
DATEPART(month(GETDATE()) -1
I understand that I used another type of DB, but I want to give a hint. I am using sql server 2019.
Firstly, you need to substitute date and only then take datepart from it.
Queries:
--dateadd -1 would subtract 1 from current month
--(Jan - 1 2022), would be December 2021
select datepart(month, dateadd(month, -1, getdate()))
--also date add covers internally the problem with 30,31 days.
--May always has 31 days, April 30. So -1 subtraction from 31th of May,would result in 30th of April.
select dateadd(month, -1, cast('2021-05-31 10:00:00' as datetime))

Data Preparation End OF Every Month - Moving Over 12 Months

I have data prep procedure in SQL. I want to have data preparation at the end of every month
Say I want the procedure run on last day of month e.g. on 31 January 2020 it should prep data from 1 January to 31 January.
So it's kind of moving window over all months of the year. Because I need data for evaluation at the end of each month.
I tried this, however, this does not give automation. Its sort of manual running end of every month
select '2020-10-01' as beginDate_AnalysisWindow
, '2020 -01-31' as endDate_AnalysisWindow
into #AnalysisWindow --create temporary table #AnalysisWindow
I also tried the following, however, I’m not sure if it does for the whole month or just one day?
SELECT START_OF_MONTH_DATE AS beginDate_AnalysisWindow
,END_OF_MONTH_DATE AS endDate_AnalysisWindow
INTO #AnalysisWindow
FROM [dbo].[Date] WITH (NOLOCK)
WHERE DATE = DATEADD(dd, - 1, CAST(GETDATE() AS DATE))
Could someone pls help me/give me some suggestions.
Thanks in advance
If you want the last day of the current month, use eomonth():
WHERE DATE = CONVERT(date, EOMONTH(GETDATE()))
Note: This assumes that the date column has no time component. If that is the case:
WHERE CONVERT(date, DATE) = CONVERT(date, EOMONTH(GETDATE()))
SQL Server will still use an index (if available) even for this type of conversion.
EDIT:
To get the current months data, one method is:
WHERE DATE <= CONVERT(date, EOMONTH(GETDATE())) AND
DATE > CONVERT(date, EOMONTH(GETDATE(), -1))
The second argument to EOMONTH() is a months offset.
You can also try:
where getdate() <= EOMONTH(GETDATE()) AND
getdate() > DATEADD(DAY, 1, EOMONTH(GETDATE(), -1))
Instead of getdate(), you can use your date column.

Report that updates yearly

I have created a report that is supposed to look at the number of baptisms at our church for the ministry year. The Ministry year runs from Aug 1 - July 31. I currently have the report set to tell me the names of anyone that has a baptism date greater than 8/1/2016. But I would need to change that year each year for it to report properly. so I wanted to use a Case statement to have it update each year, but i am getting an error message with this: (The error is in the where clause, so I didn't include the entire report)
WHERE (P.organization_id = 1) AND
((CandidateProcesses_BaptismDate68.datetime_value) between (
case
When datepart(month, getdate()) < 8 then ('8/1/'+ datepart(year, getdate()))
When datepart(month, getdate()) >7 then ('8/1/'+
datepart((year,getdate())-1))End) and Getdate())
Does anyone see why I am getting an error?
Thanks!
You are getting an error trying to add a string and a number. You could fix that using datename() rather than datepart(). But, I think this is a simpler approach:
WHERE (P.organization_id = 1) AND
year(dateadd(month, -7, CandidateProcesses_BaptismDate68.datetime_value)) = year(dateadd(month, -7, getdate()))
This subtract 7 months to get the "ministry year" and then compares that to the current date minus seven months. That is, it subtracts 7 months and then normalizes on the calendar year.
This is a bit more expensive than your version, because it cannot use an index on CandidateProcesses_BaptismDate68(datetime_value). However, I doubt the database of baptisms is so large that the query will take very long anyway. (If that is an issue, then your version can be made to work with some simple modifications.)

SQL - get last month data

I have been using this query to extract information from last month
SELECT *
FROM Member
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate()))
with the end of the year approaching, will this automatically pull Dec 2012 when i run it in Jan 2013 ?
Yes. your getdate() function will give the current date when the query is run. And you are adding -1 to the month and comparing month of date_created column and the last month. But I think you should also do comparison of year. You should add two conditions month and year both.
Yes, it will pull December data. But it will pull December data from any year, not just 2012
Yes, it will. DATEADD is a SQL internal function that adds to the full date, not just the selected part (day, month, year).