How to get YTD data in SQL - sql

where (au.[DateTime]>= DATEADD(WK,-12,GETDATE()) AND au.[DateTime]< GETDATE())
--gets everyday for the last 12 weeks
How can I modify to get every day for YTD?

where au.[DateTime] between DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0)
AND DATEADD(ms,-2,DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0))
This will get you the first day of the current year. A point i am not sure you need the And au.datetime ... since it is YTD it cannot have tomorrow data yet ? I tried -1 MS but for some reason it doesn't work. possible question.

Related

SQL connection within Excel- date range

I need to be able to look at the previous 3 months of data using a SQL statement within Excel.
I have the below code which I've been able to build but it doesn't do what I need 100%.
It gives me the last 3 months and the last date of the 4th month and the first date of the current month.
I could use Excel VBA and delete out data that is the first of current and last of the month 4 months ago.
However, I was wondering if anyone could help correct the below.
I've tried using EOMNTH and this brings an error up and I cant seem to use a DECLARE statement either.
If the below could be changed to only bring back information from the last 3 months (Jan, Feb and March) that would be great.
If someone could explain how I could change the below for only dates within the previous month that would be helpful too.
where T1."Receive_Date" between DATEADD(dd, -DAY(DATEADD(mm, -4, getdate())), DATEADD(mm, -3, getdate()))
and DATEADD(dd, -DAY(getdate()) + 1, getdate())

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 Query Subtract 1 month

I need to query SQL for data that falls into a last month date. I thought I was using the correct query logic but I get no results and I know there are results. The snippet of code is this:
MONTH(n.JOIN_DATE) = DATEADD(month, - 1, GETDATE())
This is giving me no results and I need to get anyone who has a join date of last month. What am I missing?
Use this:
MONTH(n.JOIN_DATE) = MONTH(DATEADD(month, - 1, GETDATE()))
You need to compare apples with apples, so compare the numerical month on both sides of the equation.
Massive credit to #PaulL for figuring this out before I did.
Update:
As #DasBlinkenLight and Matt pointed out, just comparing by month leaves the door open for multiple years to be returned. One possible fix would be to also compare the years, e.g.
WHERE MONTH(n.JOIN_DATE) = MONTH(DATEADD(month, - 1, GETDATE())) AND
YEAR(n.JOIN_DATE) = YEAR(DATEADD(month, - 1, GETDATE()))
MONTH(...) produces a month number. You should not compare it to the result returned by DATEADD, which is actually a date.
If you are looking for everyone who has joined less than a month ago, you can do it like this:
WHERE DATEADD(month, 1, n.JOIN_DATE) > GETDATE()
This takes into account the year and the day as well, not only the month.
If you are looking for everyone who joined last month, no matter on what day, you can use a more complex condition:
WHERE MONTH(DATEADD(month, -1, GETDATE()) = MONTH(n.JOIN_DATE)
AND YEAR (DATEADD(month, -1, GETDATE()) = YEAR (n.JOIN_DATE)
The second condition is necessary to avoid confusion between members joining last month and members joining on the same month one or more years ago.
MONTH(n.JOIN_DATE) returns a numeric which indicate the month in date m.JOIN_DATE
DATEADD(month, - 1, GETDATE()) returns a date which indicate date in last month.
So, you can use this instead :
MONTH(n.JOIN_DATE)= MONTH(DATEADD(month, - 1, GETDATE()))
OR
n.JOIN_DATE = DATEADD(month, - 1, GETDATE())
MONTH(n.JOIN_DATE) will only return the numerical value of the month (e.g.: 11 or 5).
DATEADD(MONTH, -1, GETDATE()) will simply subtract one month from the current date. It is still in a DATETIME format.
You may be looking for:
MONTH(n.JOIN_DATE) = MONTH(DATEADD(MONTH, -1, GETDATE()))
SELECT
DATEFROMPARTS(YEAR(DATEADD(month,-1,GETDATE())),MONTH(DATEADD(month,-1,GETDATE())),1) AS StartOfLastMonth
,DATEADD(day,-1,(DATEFROMPARTS(YEAR(GETDATE()),MONTH(GETDATE()),1))) AS EndOfLastMonthAsDate
,DATEADD(day,-3,CAST(DATEFROMPARTS(YEAR(GETDATE()),MONTH(GETDATE()),1) AS DATETIME)) AS EndOfLastMonthMidngith
,CAST(DATEADD(month,-1,GETDATE()) AS DATE) AS OneMonthAgoStrartOfDay
,CAST(GETDATE() AS DATE) AS StartOfToday
,DATEADD(MS,-3,CAST(CAST(GETDATE() AS DATE) AS DATETIME)) AS MidnightLastNight
Okay As people have definitely illustrated there are a lot of different answers to your question and all are built upon similar premise. using DATEADD() with a negative number to go back a month. Or to compare month and year to see if they are the same. The former being geared at 1 month ago to today and the later being last month.
All of the answers so far, expect #DasBlinkenLight and #TimBiegeleisen, fail to take into account TIME component of your column and the GETDATE() function if you have one. If your column is DATETIME you will need to take that into account. The above SELECT query that will arm you with some ways of getting to different dates that i suspect will meet your needs.
As far as using BETWEEN with dates be careful! because the values you put in are inclusive so if you put GETDATE() on the right side of the between statement you will get today's results too but you might really want UP TO to today in which case you should change your right side argument. Also I am not sure about Oracle, mysql, etc. but Micrsofot SQL-Server is accurate to .003 milliseconds. So if you really want to look at midnight of a date you should look at 23:59:59.997 because .998 and .999 will round up to the next day.
Also to further simplify if you don't want time components you can also cast your column to DATE and it essentially drops off the time and the BETWEEN because a little clearer too, e.g. CAST(n.JOIN_DATE AS DATE)
There are definitely other questions on this subject on stackoverflow I encourage you to research.
I knew this was a simple one and I was missing something to it. My code was wrong based upon the many responses I received on this and I was comparing apples to oranges and not apples to apples. Once I added the Month() around the dateadd function, it worked.
The reply to this answer are correct. But in the light of best practice writing your query this way will make it less SARGABLE, hence making it ignore indexes if you have one. It might be better to write it as
WHERE n.JOIN_DATE between DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) AND DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)
based on the comment below I have modified the query. I guess I did not read the question in depth.

Trying to track progress this month vs Previous

This sounded simple but it doesnt work like I thought.
I am trying to track progress for Month to date
Here is my code for MTD
Startdate>=DATEADD(MONTH, DATEDIFF(MONTH, 0, Convert(date, getdate())), 0)
Its extremely simple.
For Last Months Start I use:
Startdate>= DATEADD(month, DATEDIFF(month, -1, getdate()) , 0)
as the start date
and for the current marker I used this:
Enddate>=DATEADD(month, DATEDIFF(month, 0, getdate()-30), 0)+datepart (day,getdate())
Ideally I want to know that if today is the 5th. How many sales took place in that window.
then I want to also know how we did in the same period the last month.
My problem is I find on months with 31 days that follow months with 29 days I have issues.
Is there a function that gives me the same date a month ago ?
dateadd(month, -1, getdate())
i.e. dateadd(month, -1, '20150330') returns '2015-02-28'
If exact day doesn't exist in previous month returns last day of month.

SQL Server - Quarterly data Report

I have recently wrote a query (stack overflow helped) to generate annual data from a database.
the logic used is : any day in this year will always give all the results from last year.
where year (table.datecolumn) = year(GETDATE())-1
Now, I have been asked to do a similar thing with quarterly data and I am having a hard time as I am not very experienced in writing these kinds of queries.
I want something that I can schedule a ssrs report with- that gives me all the data for each quarter without using real dates. so that I could schedule this to run on Jan 1st, April 1st, July 1st, Oct 1st.
Thank you.
Here is query to get all data for the previous quarter
SELECT *
FROM myTable
WHERE MyDate >= DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 1, 0)
AND MyDate < DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0)
This way you can run it any time after the next quarter starts and before it ends it will still produce same results without having to specify dates.