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).
Related
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.
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))
Tried to add a custom Fiscal Week column to my DimDate table in a query.
Some background: the fiscal year always begins on 02-01 [February 1]. My DimDate tables earliest date goes to January 01, 2008 [01-01-2008]. I looked at previous posts and tried in the code below, except I got 0 for the Week Number for 02-01-2008 and 02-02-2008.
Datediff(wk, CONVERT(DATE, '2008-02-01'), CONVERT(DATE, dbo.DIMDATE.DATE_VALUE)) AS 'FiscalWeek',
If I followed you correctly, you can just offset the date by 1 month:
datepart(wk, dateadd(month, -1, datevalue)) as fiscal_week
Depending on your actual requirement, you might want to try isowk as well.
I'm trying to return some data based on a series of weeks. This is going to be for an SSRS report.
For example, I need to return all rows which are dated from 3rd July to 9th July inclusive (Sun-Sat), name it Week 1 of the month. Then 10th Jul to 16th July, which is Week 2, and so forth. The hardest part is having it continue on between months. For example, 26th June to 2nd July.
I'm sure I can use DATEPART to do this somehow, but really have no idea how. Can someone offer assistance?
Thank you in advance.
DATEPART(week, DateField) will give you the week of the year, which will cover your criteria. Week of the month is not a great criteria to use since it's so amorphous.
You can get the week of the year for the first of the month by returning DATEPART(week, '7/1/2011') or whatever, which will give you a starting point.
EDIT:
For your additional criteria from the comments:
SELECT <fields>
FROM MyTable
WHERE YEAR(DateField) = 2011
AND DATEPART(week, Datefield) BETWEEN
DATEPART(week, '6/1/2011') AND DATEPART(week, (DATEADD(DAY, -1, (DATEADD(Month, 1, '6/1/2011')))))
You may want to check the closing parentheses count, but basically this says:
Year 2011
Week of 6/1/2011 through Week of 6/30/2011
The extra date calculations are to get to 7/1/2011 (month +1) then back a day to 6/30/2011. The alternative is to hardcode date breaks for each month. This way you can also paramterize the dates and concatenate like
CAST(#Month + '/1/' + #Year as smalldatetime)
I suggest the use of something similar to a date dimension. There are tons of examples of how you do this. Here is one:
http://prologika.com/CS/forums/p/517/2094.aspx
Well I will give a more exact answer because no one has left anything yet
Declare #myDate datetime = getdate()
select DATEPART(week, #myDate) - DATEPART(week,CONVERT(DATETIME, DATENAME(mm, #myDate)+"/01/"+ DATENAME(yyyy, #myDate) ))-1
This should give you a good approximation you might want to check my parens.
This one has bugged me for a while now. Recently when revisiting some code I wrote for a customer a few years ago I was wondering if there is a more elegant solution to the problem.
The customer stores all of their clients information including date of birth (date time field)
They run an extract every Monday that retrieves any customer whose birthday will fall within the following week.
I.e. if the extract was run on Monday Jan 1st, Customers whose birthday fell between (and including) Monday Jan 8th -> Sunday Jan 14th would be retrieved.
My solution was to use the Datepart(dy) function and calculate all upcoming birthdays based off the customers date of birth converted to day of year, adding some logic to include for the extract being run at the end of a year.
The problem was that using Day of year throws results off by 1 day if the customer was born on a leap year and / or the extract is run on a leap-year after the 29th of Feb, so once again I had to add more logic so the procedure returned the expected results.
This seemed quite over-kill for what should be a simple task
For simplicity let’s say the table 'customer' contains 4 fields, first name, last name, dob, and address.
Any suggestions on how to simplify this would really be appreciated
Wes
Would something like this work for you?
select * from Customers c
where dateadd(year, 1900-year(dob), dob)
between dateadd(year, 1900-year(getdate()), getdate())
and dateadd(year, 1900-year(getdate()), getdate())+7
Why not use DATEPART(wk) on this year's birthday?
SET DATEFIRST 1 -- Set first day of week to monday
SELECT * FROM customer
WHERE DATEPART(wk, DATEADD(yy, DATEPART(yy, GETDATE()) - DATEPART(yy, customer.dob), customer.dob)) = DATEPART(wk, GETDATE()) + 1
It selects all customers who's birthday's weeknumber is one greater than the current weeknumber.
I think DATEADD should do the proper thing.
YEAR(GETDATE() - dbo.Patients.Dob) - 1900
I can safely assume you will never have customers born before 1900
Please Try This one.
SELECT TOP 10 BirthDate, FirstName
FROM Customers
WHERE DATEPART(mm,BirthDate) >= DATEPART(mm,GETDATE())
AND DATEPART(day,BirthDate) >= DATEPART(day,getdate())
OR DATEPART(mm,BirthDate) > DATEPART(mm,getdate())
ORDER BY DatePart(mm,BirthDate),DatePart(day,BirthDate)
this query will get upcoming birthdays including today itself