Case Statement with Datediff and DatePart - sql

Can some one help with a case statement please, what I need is the query to show is the following. I know there are ways to do this easier but I just need help on the Case Statement.
--If the Current Month is ‘Less Than’ the DOB Month, then take ‘1’ of the Total Years to give me 41.
--If the Current Month is ‘Greater Than’ the DOB Month then the Age is Correct.
--However if the Current Month is ‘Equal’ to the DOB Month then we need to go to Day level to get the correct Age.
Set #DOB = '01 November 1971'
Set #Today = GETDATE()
SELECT Datediff(Year,#DOB,#Today) AS Years,
Datepart(Month,#DOB) As DOB_Month,
Datepart(Day, #DOB) as DOB_Day,
DatePart(Month, #Today) As Current_Month,
Datepart(Day,#Today) AS Current_Day

Try this :
DECLARE #DOB DATE= '01 November 1971'
DECLARE #TODAY DATE = GETDATE()
SELECT CASE
WHEN DATEPART(MONTH, #TODAY) < DATEPART(MONTH,#DOB) THEN DATEDIFF(YEAR,#DOB,#TODAY) - 1
WHEN DATEPART(MONTH, #TODAY) > DATEPART(MONTH,#DOB) THEN DATEDIFF(YEAR,#DOB,#TODAY)
ELSE
CASE
WHEN DATEPART(DAY, #TODAY) < DATEPART(DAY,#DOB) THEN DATEDIFF(YEAR,#DOB,#TODAY) - 1
ELSE DATEDIFF(YEAR,#DOB,#TODAY)
END
END

You can try this :
case
when DatePart(Month, #Today) > Datepart(Month,#DOB) then Datediff(Year,#DOB,#Today)
when DatePart(Month, #Today) < Datepart(Month,#DOB) then (Datediff(Year,#DOB,#Today) - 1)
when DatePart(Month, #Today) = Datepart(Month,#DOB) then
case
when DatePart(Day, #Today) >= Datepart(Day,#DOB) then (Datediff(Year,#DOB,#Today) )
when DatePart(Day, #Today) < Datepart(Day,#DOB) then (Datediff(Year,#DOB,#Today) - 1 )
end
end as AgeCompleted,

declare #DOB date = '19680411'
select datediff(year, #DOB, getdate())- case when month(#DOB)*32 + day(#DOB) >
month(getdate()) * 32 + day(getdate()) then 1 else 0 end

Related

How to extract data from 1st day of the month till today's date -1

I am trying to extract all the data that has the datetime from 1st day of the month till yesterday, for example:
01/06/2017 - 22/06/2017
I have used this code:
Select *
from testDb.dbo.Company1
WHERE MONTH(CreatedDate) = MONTH(dateadd(dd, -1, GetDate())) AND
YEAR(CreatedDate) = YEAR(dateadd(dd, -1, GetDate()))
EDIT
My column for CreatedDate, its data type is DateTime. Not sure if there is any difference tho.
But this prints out all the data from 01/06/2017 - 23/06/2017. What code should I write such that it will print all data till (today's date-1)? Thanks for the help and have a great day!
Instead of comparing the month and year components separately, try bounding your result set using a range of two complete data points, one being the start of the month, and the other being yesterday.
SELECT *
FROM testDb.dbo.Company1
WHERE
CreatedDate BETWEEN DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) AND
DATEADD(day, -1, CAST(GETDATE() AS date))
Demo
Try this query --
SELECT *
FROM testDb.dbo.Company1
WHERE DATEPART(Month, CreatedDate) = Datepart(Month, GETDATE())
AND DATEPART(Day, CreatedDate) <= DATEPART(Day, Getdate())
Edit:
SELECT *
FROM testDb.dbo.Company1
WHERE DATEPART(Month, CreatedDate) = Datepart(Month, GETDATE())
AND DATEPART(Day, CreatedDate) < DATEPART(Day, Getdate())
Edit 2:
SELECT CONVERT(VARCHAR(30),CreatedDate,120) As [CreatedDate]
FROM testDb.dbo.Company1
WHERE DATEPART(Month, CreatedDate) = Datepart(Month, GETDATE())
AND DATEPART(Day, CreatedDate) < DATEPART(Day, Getdate())
This though wont work when today is the first day of the month
SELECT *
FROM your_table
WHERE createdDate BETWEEN
CAST('1 ' + DateName(month, GetDate()) + ' ' +Year(GetDate()) as datetime)
AND DATEADD(day, -1, GETDATE() )
I think this where clause does what you want:
where createdDate >= dateadd(month, 0, datediff(month, 0, getdate())) and
createdDate < cast(getdate() as date)

Accumulating data from previous year

I'm having trouble with finding a solution for below SQL-query. My first query should and does the trick of accumulating amount of last year's data.
CASE
WHEN rehuv.VER_DATUM >= dateadd(year, -1, dateadd(month, -datepart(month, #STARTDATE) + 1, #STARTDATE))
AND rehuv.VER_DATUM <= DATEADD(year, -1, #ENDDATE) THEN rehuv.BELOPP ELSE 0
END AS PREVIOUS_YEAR_ACC
But when I try to accumulate data within a specific time interval (I want the same time interval as #startdate -> #enddate but one year backwards). Sql-query:
CASE
WHEN rehuv.VER_DATUM >= DATEADD(year, -1, #STARTDATE)
AND rehuv.VER_DATUM <= DATEADD(year, -1, #ENDDATE) THEN rehuv.BELOPP ELSE 0
END AS PREVIOUS_YEAR_MONTH
Thank you in advance!
Best regards,
Simon
If you want the monthly sum of last year, you can try this:
DECLARE #STARTDATE DATETIME;
DECLARE #ENDDATE DATETIME;
SET #STARTDATE='2015-1-1';
SET #ENDDATE='2015-5-1';
DECLARE #LAST_YEAR DATE;
SET #LAST_YEAR = DATEADD(YEAR, -1, DATEADD(DAY,
DATEPART(DAYOFYEAR, GETDATE())*-1+1, CONVERT(DATE, GETDATE())));
SELECT DATEADD(MONTH, DATEPART(MONTH, VER_DATUM), #LAST_YEAR) MONTH, SUM(CASE
WHEN REHUV.VER_DATUM >= DATEADD(YEAR, -1, #STARTDATE)
AND REHUV.VER_DATUM <= DATEADD(YEAR, -1, #ENDDATE)
THEN REHUV.BELOPP ELSE 0
END ) AS PREVIOUS_YEAR_MONTH
FROM REHUV
GROUP BY DATEPART(MONTH, VER_DATUM)

How to get this condition in where clause of Sql

I have a query which gives me the last month's completed data
select * from Tabl
where datepart(month, completed_date) = DATEPART(month, getDate())-1
and datepart(year, completed_date) = datepart(year, getDate())
But it gives me wrong data when the current date is in january
How can I write the condition to return correct data if the current month is January?
SQL Server's DATEADD function will help you here.
select * from Tabl
where datepart(month, completed_date) = DATEPART(month, DATEADD(MM,-1,getDate()))
and datepart(year, completed_date) = datepart(year, DATEADD(MM,-1,getDate()))
The 'MM' used is just a keyword for Month.
Well, try subtracting one month from the date instead:
select *
from Tabl
where month(completed_date) = month(dateadd(month, -1, getdate()) and
year(completed_date) = year(dateadd(month, -1, getdate());
But, if you have an index on completed_date, it is better to put all the operations on getdate() so the expression is "sargable" (that is, an index can be used):
where completed_date >= cast(dateadd(month, -1, getdate() - day(getdate() + 1) as date) and
completed_date < cast(getdate() - day(getdate())
When you subtract the "day of the month" from the date, you get the last day of the previous month.
select * from Tabl
where
datepart(year, completed_date) * 100 + datepart(month, completed_date)
<
datepart(year, getDate()) * 100 + datepart(month, GetDate())

Finding the list of people who have birthday this week

I am trying to list the people who have birthday this week with this code:
declare #START_DATE date;
set #START_DATE = DATEADD(dd, 1 - DATEPART(dw, getdate()), getdate())
declare #END_DATE date;
set #END_DATE = DATEADD(dd,6, #START_DATE)
set DATEFIRST 1
SELECT #START_DATE as StartDate, Personel.DogumTarihi , #END_DATE as EndDate
,[Adi]
,[Soyadi]
,[BirimAdi]
,[DogumTarihi]
,[MudurlukAdi]
,[Gorevi]
,[CepTelefonu]
,[EvTelefonu]
from Personel
where (
DATEPART(m, Personel.DogumTarihi) = DATEPART(m, #START_DATE)
and DATEPART(DAY, Personel.DogumTarihi) >= DATEPART(DAY, #START_DATE)
and DATEPART(DAY, Personel.DogumTarihi) <= DATEPART(DAY, #END_DATE)
)
OR (
DATEPART(m, Personel.DogumTarihi) = (DATEPART(m, #START_DATE)+ 1)
and DATEPART(DAY, Personel.DogumTarihi) <= DATEPART(DAY, #END_DATE)
)
First I set the start date and calculate the end date according to start date. Then I set Monday as the first day of week.
But everytime I run this, I receive a different Start date. I am quite new to Ms Sql Scripting, I may be doing sth wrong in the declarations but I couldn'd find it. Thanks in advance.
Try this:
SELECT DATEADD(WEEK, DATEDIFF(DAY, 0, GETDATE())/7, 0) FirstDayOfCurrentWeek,
DATEADD(YEAR, DATEDIFF(YEAR, DogumTarihi, GETDATE()), [DogumTarihi]) BirthdayThisYear,
DATEADD(WEEK, 1, DATEADD(WEEK, DATEDIFF(DAY, 0, GETDATE())/7, 0)) FirstDayOfNextWeek
,[Adi]
,[Soyadi]
,[DogumTarihi]
,[BirimAdi]
,[MudurlukAdi]
,[Gorevi]
,[CepTelefonu]
,[EvTelefonu]
FROM Personel
WHERE DATEADD(YEAR, DATEDIFF(YEAR, [DogumTarihi], GETDATE()), [DogumTarihi]) >= DATEADD(WEEK, DATEDIFF(DAY, 0, GETDATE())/7, 0)
AND
DATEADD(YEAR, DATEDIFF(YEAR, [DogumTarihi], GETDATE()), [DogumTarihi]) < DATEADD(WEEK, 1, DATEADD(WEEK, DATEDIFF(DAY, 0, GETDATE())/7, 0))
ok, one more attempt:
where
case when year(#START_DATE) = year(#END_DATE) THEN '1' ELSE CASE WHEN month(#birthdate) = 12 THEN '0' WHEN month(#birthdate) = 1 THEN '1' ELSE '9' END END
+ RIGHT('0' + CONVERT(varchar(2), MONTH(#birthdate)),2)
+ RIGHT('0' + CONVERT(varchar(2), DAY(#birthdate)),2)
between
case when year(#START_DATE) = year(#END_DATE) THEN '1' ELSE '0' END
+ RIGHT('0' + CONVERT(varchar(2), MONTH(#START_DATE)),2)
+ RIGHT('0' + CONVERT(varchar(2), DAY(#START_DATE)),2)
and
'1'
+ RIGHT('0' + CONVERT(varchar(2), MONTH(#END_DATE)),2)
+ RIGHT('0' + CONVERT(varchar(2), DAY(#END_DATE)),2)
sql should let you specify the week directly
DATEPART(ww,GETDATE())
or in oracle: to_char( mydate, 'ww' )
In order to cope with the my problem I revised the code above according to answers:
set DATEFIRST 1
declare #START_DATE date;
set #START_DATE = DATEADD(dd, 1 - DATEPART(dw, getdate()), getdate())
declare #END_DATE date;
set #END_DATE = DATEADD(dd,6, #START_DATE)
SELECT #START_DATE as StartDate,
(case when
(DATEPART(m, #START_DATE) = DATEPART(m, #END_DATE))
then
(case when (DATEPART(DAY, Personel.DogumTarihi) >= DATEPART(DAY, #START_DATE) and DATEPART(DAY, Personel.DogumTarihi) <= DATEPART(DAY, #END_DATE)) then Personel.DogumTarihi else 0 end)
else
(case when DATEPART(m, Personel.DogumTarihi) = DATEPART(m, #START_DATE)
then
(case when (DATEPART(DAY, Personel.DogumTarihi) >= DATEPART(DAY, #START_DATE)) then Personel.DogumTarihi else 0 end)
else
(case when (DATEPART(DAY, Personel.DogumTarihi) <= DATEPART(DAY, #END_DATE)) then Personel.DogumTarihi else 0 end)
end
)
end),
#END_DATE as EndDate, [TCKN]
,[Adi]
,[Soyadi]
,[BirimAdi]
,[DogumTarihi]
,[MudurlukAdi]
,[Gorevi]
,[CepTelefonu]
,[EvTelefonu]
,[VakifTelefonu]
from Personel where
DATEPART(m, #START_DATE) = DATEPART(m, #END_DATE)
OR DATEPART(m, Personel.DogumTarihi) = DATEPART(m, #START_DATE)
OR DATEPART(m, Personel.DogumTarihi) = DATEPART(m, #END_DATE)
Now it is taking the case where "the start and end date of the month are in the same week (like this week)" into account. It looks like it is bringing right results..
Let's have a try:
declare #today datetime
set #today = getdate()
-- erase the hours
set #today = dateadd(hh, -datepart(hh, #today), #today)
-- erase the minutes
set #today = dateadd(mi, -datepart(mi, #today), #today)
-- erase the seconds
set #today = dateadd(ss, -datepart(ss, #today), #today)
-- erase the milliseconds
set #today = dateadd(ms, -datepart(ms, #today), #today)
-- go to start of current week (sunday!)
set #today = dateadd(dd, 1-datepart(dw, #today), #today)
select * from MYTABLE
where DATECOL between
dateadd(yy, datepart(yy, DATECOL) - datepart(yy, #today), #today) and
dateadd(d, 7, dateadd(yy, datepart(yy, DATECOL) - datepart(yy, #today), #today))
Apparently SqlServer 2012 has a DATEFROMPARTS function, in 2005 we will have to use this roundabout way to trim a date.
To select a birthday, I exchange the "today's year" for the record's year. For the end-date of the range I add 7 days to that. Note that you want to search from sunday 0:00 to saturday 23:59.
This will probably still fail if halfway during the week a new year starts and the birthday you want is in the new year.

SQL - Get Numerical Day of Month/Quarter

Using SQL Server 2005:
How can I get the numerical day of the month and day of the quarter in a query?
DECLARE #DATE DATETIME
SET #DATE = GETDATE()
SELECT DATEPART(dy, #DATE) AS DayOfYear
--, <something> AS DayOfQuarter
--, <something> AS DayOfMonth
, DATEPART(dw, #DATE) AS DayOfWeek
Thanks in advance!
DECLARE #DATE DATETIME
SET #DATE = GETDATE()
SELECT DATEPART(dy, #DATE) AS DayOfYear
, DATEDIFF(d, DATEADD(qq, DATEDIFF(qq, 0, #DATE), 0), #DATE) + 1 AS DayOfQuarter
, DAY(#Date) AS DayOfMonth
, DATEPART(dw, #DATE) AS DayOfWeek
As for the day of quarter, this will demande a bit of further investigate on my side. Despite, I guess that for the day of month, this would simply be the date itself:
select DATEPART(D, #DATE)
SELECT
DATEPART(year, '12:10:30.123')
,DATEPART(month, '12:10:30.123')
,DATEPART(day, '12:10:30.123')
,DATEPART(dayofyear, '12:10:30.123')
,DATEPART(weekday, '12:10:30.123');