How to get the Next months results from date field - sql

I have a table with a date.
I need to get all results for the upcoming month.
*******Sample Code I have but it returns 2 months of data**********
where worktype = 'mpm' and status = 'active'
and (nextdate >= DATEADD(MONTH,01,GETDATE()))
and (nextdate < DATEADD(MONTH,02,GETDATE()))
Some Data:
2016-01-27 00:00:00.000
2016-01-28 00:00:00.000
2016-02-02 00:00:00.000
2016-02-02 00:00:00.000
It is returning 2 months of data.

Your results are returning exactly what you've requested. You're requesting to get anything within the date range of One Month from Today and Two Months from Today.
All of your results are within that range.
If you are only interested in the data that is within the next calendar month (at the time of writing, January 2016), this would suit you better:
Where worktype = 'mpm'
And status = 'active'
And nextdate Between
DateAdd(Month, -1, DateAdd(Month, DateDiff(Month, 0, GetDate()) +2, 0))
And DateAdd(Day, -1, DateAdd(Month, DateDiff(Month, 0, GetDate()) +2, 0))
If you are using SQL Server 2012 or later, you can also use the following:
Where worktype = 'mpm'
And status = 'active'
And nextdate Between
DateAdd(Day, 1, EOMonth(Current_Timestamp))
And EOMonth(DateAdd(Day, 1, EOMonth(Current_Timestamp))

Something like this maybe:
WHERE DATEPART(MONTH, nextdate) = DATEPART(MONTH,DATEADD(MONTH,1,GETDATE()))

Related

Return data 2 years back same month previous week with date range

I am trying to extract 2 years ago data with date range greater than 07/01/2019 and 2 years ago same month and week. Need suggestions on date conversion as well
select
tilr.BusinessUnitID
,emph.employeeID
,convert(varchar(10), cast(cast(tilr.date_key as varchar(10)) as date), 101) as ConvertDate
,tilr.paidhr as 'Paid hr'
from [dbo].[location] tilr
inner join [dbo].[Employee] emph
on emph.employeeID = tilr.employeeID
and emph.businessunitid = tilr.BusinessUnitID
and emph.date_key = tilr.date_key
where
tilr.date_key >= 20190701
and datename(year, convert(varchar(10), cast(cast(tilr.date_key as varchar(10))as date), 101))
< DateAdd(YY, -2, GETDATE())
Trying to get data for date range >= 07/01/2019 and < 10/23/2019 ( +/- days of same month 2 years ago) for comparison. With above query I'm getting data till end of the year 12/2019 instead of 10/2019.
Sample data
BusinessUnitID employeeID ConvertDate Paid hr
1234 1 07/01/2019 1.4
2345 2 10/25/2019 3.5
It looks like you need something like the following condition
tilr.date_key >= DATEADD(month, -2, DATEFROMPARTS( YEAR(GETDATE()) - 2, MONTH(GETDATE()), 1 )) AND
tilr.date_key < DATEADD(month, 1, DATEFROMPARTS( YEAR(GETDATE()) - 2, MONTH(GETDATE()), 1 ))
Note how calculations only use date functions, not conversion to/from varchar, and that there are no functions on the actual column value. This means that indexes can be used efficiently.

First date of current Fiscal Year

I am trying to get the First Date of the current Fiscal year. In my case the Fiscal year starts in Oct.
Example: I need the 10/01/2015
I would generally use the below query to the get the first day of the current year but how do I change it to get the first date of fiscal year?
select
convert(varchar(12), (
DateAdd(month, (
Month(getdate()) - 1) * -1,
DateAdd(Day, (
Day(getdate()) - 1) * -1,
getdate()))),
103) as StartYear
You can apply following logic: Subtract 9 months from the current date, find Jan 1st of this year and add 9 months again:
DATEADD(MONTH, 9, DATEADD(YEAR, DATEDIFF(YEAR, 0, DATEADD(MONTH, -9, GETDATE())), 0))
declare #fiscal date = '2015-10-01'
; with dates
as
(
select date = '2015-09-30' union all
select date = '2015-10-01' union all
select date = '2016-09-30' union all
select date = '2016-10-01'
)
select *,
fiscal = case when date < dateadd(year, year(date) - year(#fiscal), #fiscal)
then dateadd(year, year(date) - year(#fiscal) - 1, #fiscal)
else dateadd(year, year(date) - year(#fiscal), #fiscal)
end
from dates
/* result
date fiscal
---------- ----------
2015-09-30 2014-10-01
2015-10-01 2015-10-01
2016-09-30 2015-10-01
2016-10-01 2016-10-01
*/
At first Subtract 9 months from current date to get the previous year(your Fasical year).
Then take the year difference with 0 to your date.
Now add the year difference with 0 to get the starting of a month.
Finally you need to add the 9 months to get the starting month of a Fasical Year.
As year example the require format "10/01/2015". So get that you can use convert function with 101.
select convert(varchar(12), DATEADD(MONTH, 9, DATEADD(YEAR, DATEDIFF(YEAR, 0, DATEADD(MONTH, -9, GETDATE())), 0)), 101) as StartYear

How can I get the last 12 months from the current date PLUS extra days till 1st of the last month retrieved

Getting the last 12 months from a specific date is easy and can be retrieved by the following command in SQL-server. Its answer is 2014-08-17.
select Dateadd(Month, -12, '2015-08-17')
What I want is to get the last 12 months but ending at 2014-08-01 (in the above case) instead of any where in the middle of the month.
SELECT dateadd(month,datediff(month,0,getdate())-12,0)
Result is
-----------------------
2014-08-01 00:00:00.000
So the where clause should be
WHERE datecol >=dateadd(month,datediff(month,0,getdate())-12,0)
to get all data starting from jan 01 of last year's same month
Using DATEADD and DATEDIFF:
DECLARE #ThisDate DATE = '20150817'
SELECT DATEADD(YEAR, -1, DATEADD(MONTH, DATEDIFF(MONTH, '19000101', #ThisDate), '19000101'))
For more common date routines, see this article by Lynn Pettis.
To use in your WHERE clause:
DECLARE #ThisDate DATE = '20150817'
SELECT *
FROM <your_table>
WHERE
<date_column> >= DATEADD(YEAR, -1, DATEADD(MONTH, DATEDIFF(MONTH, '19000101', #ThisDate), '19000101'))
If you want all the records since the first day of the current month last year, then you can use:
where <somedate> >= dateadd(day, 1 - day(dateadd(month, -12, getdate()),
dateadd(month, -12, getdate()))
For all days except Feb 29th, you can use the simpler:
where <somedate> >= dateadd(day, 1 - day(getdate()),
dateadd(month, -12, getdate))

Why do I get different results with this SQL Date Part and date parameters

When I run this where clause on my table I get 2 different results and to me its seems like I should get the same number of records back.
The one I'm using just a static date to test and the other should also retrieve the same results where I'm trying to get last month results
I idea the query is a report that will automatic load the previous months records.
WHERE
(OrderReceiptedDate >= '2015-03-01')
AND (OrderReceiptedDate <= '2015-03-31')
WHERE
(DATEPART(mm, OrderReceiptedDate) = DATEPART(mm, DATEADD(mm, - 1, GETDATE())))
AND
(DATEPART(yy, OrderReceiptedDate) = DATEPART(yy, DATEADD(mm, - 1, GETDATE())))
These are the two statements
WHERE (OrderReceiptedDate >= '2015-03-01' AND
OrderReceiptedDate <= '2015-03-31'
)
WHERE (DATEPART(month, OrderReceiptedDate) = DATEPART(month, DATEADD(month, - 1, GETDATE()))) AND
(DATEPART(year, OrderReceiptedDate) = DATEPART(year, DATEADD(month, - 1, GETDATE())))
Given that today is April 2015, you are expecting that both of these get all dates for March. And, they would, if your dates had no time components. The problem is that almost any datetime on March 31st is not going to match the first condition. The one exception is exactly at midnight: 2015-03-01 00:00:00.000.
The first is better written as:
WHERE (OrderReceiptedDate >= '2015-03-01' AND
OrderReceiptedDate < '2015-04-01'
)
A better way to write "get me last months date" is something like:
WHERE OrderReceiptedDate >= dateadd(month, -1, cast(getdate() - day(getdate()) + 1 as date)) and
OrderReceiptedDate < cast(getdate() - day(getdate()) + 1 as date)
This does all the calculations on getdate() so the query could still take advantage of an index on OrderReceiptDate.

SQL Server 2008 Count(Distinct?

ApptStart
2005-02-18 10:00:00.000
2005-02-18 13:00:00.000
2005-02-18 11:00:00.000
2005-02-21 09:00:00.000
2005-02-18 15:30:00.000
2005-02-18 14:30:00.000
.
.
.
I have a column in our database that looks like the above. I want to count appointments for the month for a given doc. On Fridays most of them do a half day. So I do not want to count Fridays with appointments only in the morning. If the appointment is in the afternoon, after 12:00:00.000 I want to include that day in the distinct count.
So far I have:
SELECT
ScheduleDays = count(distinct CONVERT(datetime, convert(char(12), a.ApptStart, 1)))
FROM Appointments a
WHERE
ApptKind = 1 AND
--filter on current month
a.ApptStart >= ISNULL(DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0),'1/1/1900') AND
a.ApptStart < ISNULL(DATEADD(month, DATEDIFF(month, 0, GETDATE())+1, 0),'1/1/3000') AND
--Filter on doctor
a.ResourceID in (201)
This worked when I counted every day with appointments on it, but like I said I need to exclude those half days.So I was thinking about only looking at the last right chars of the ApptStart and comparing it x > noon in a case inside the distinct count...
I tried the following, but it did not work:
ScheduleDays = count(distinct case when (Right(a.ApptStart, 12)) > '12:00:00:000' then 1 else 0 END)
Thanks in advance!
EDIT
I tried:
SELECT
ScheduleDays=COUNT(DISTINCT(CAST(datediff(d,0,a.ApptStart) as datetime)))
FROM Appointments a
WHERE
ApptKind = 1 AND
--filter on current month
a.ApptStart >= ISNULL(DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0),'1/1/1900') AND
a.ApptStart < ISNULL(DATEADD(month, DATEDIFF(month, 0, GETDATE())+1, 0),'1/1/3000')AND
--filter all days that aren't Friday, and then give you all Fridays with an hour > 12.
DATENAME(weekday, a.ApptStart) <> 'Friday' OR DATEPART(hour, a.ApptStart) > 12 AND
--Filter on doctor
a.ResourceID in (201)
for 1808 as the count
You probably want to treat dates as dates, rather than strings. You can determine whether a particular timestamp is on a Friday -- or the hour of a timestamp -- using DATEPART, without having to CONVERT it into a CHAR:
datename(weekday, timestamp_value) -- returns Friday
datepart(weekday, timestamp_value) -- returns either 5 or 6, depending on the value of SET DATEFIRST. (Get day of week in SQL 2005/2008)
datepart(hour, timestamp_value) -- returns hour part
Using these, you can test whether a timestamp is on Friday at or after noon by checking if datepart(weekday, timestamp_value) = 6 and datepart(hour, timestamp_value) >= 12.
bendataclear pointed out that you're using distinct on a case statement which can only ever return 0 or 1, so your total will only ever be 0, 1, or 2. If you're trying to determine which days the doctors worked more than half a day, you'll need to select distinct dates --
SELECT COUNT(DISTINCT(CAST(datediff(d,0,timestamp_value) as datetime)))
FROM table_name
WHERE DATENAME(weekday, timestamp_value) <> 'Friday' OR DATEPART(hour, timestamp_value) > 12
AND the rest of your filters here
The WHERE clause there will give you all days that aren't Friday, and then give you all Fridays that have an hour > 12.