I have a question regarding finding birthdays according to the date they were born, sadly I haven't found an answer for this on this website.
I want the set a number foreach date that has X days away from being their birthday. Except i have a hard time using their DOB and datediff.
What I want:
John: 0 --Today his birthday
Eric:0
Ben:1 -- In this week
Jerry:1
Jules: 2 -- In this month
Tom: 3 -- all other dates
I have tried using DATEDIFF
with format but the issue is that you can't use a format with DATEDIFF
.
I tried without and this returned their birth dates.
This is the code I tried:
SELECT *
FROM
(SELECT
[id],
[fullname] = CONCAT(E.[name],
(CASE
WHEN LEN(E.[preposition]) > 0
THEN ' ' + E.[preposition]
END),
', ', E.[givenname]),
[relationnumber],
[day] = (CASE
WHEN DATEDIFF(day, [birthday], '2021-09-09') < 1
THEN 0
WHEN DATEDIFF(day, [birthday], '2021-09-09') < 8
THEN 1
WHEN DATEDIFF(day, [birthday], '2021-09-09') < 31
THEN 2
ELSE 3
END),
[birthday]
FROM
[info].[member] E
WHERE
[system_active] = 1) A
ORDER BY
day ASC
Note: the set date '2021-09-09' I get from URL
Thanks in advance
Edit My (working) Solution
SELECT *
FROM (
SELECT [id]
,[fullname] = CONCAT(E.[name], (CASE WHEN LEN(E.[preposition])>0 THEN ' '+E.[preposition] END), ', ', E.[givenname])
,[relationnumber]
,hi = DATEADD(year, DATEDIFF(year,[birthday], CAST('2021-09-09' as date)) , [birthday])
,[day] =
(
CASE
WHEN DATEDIFF(day, '2021-09-09', DATEADD(year, DATEDIFF(year,[birthday], CAST('2021-09-09' as date)) , [birthday])) = 0 THEN 0
WHEN DATEDIFF(day, '2021-09-09', DATEADD(year, DATEDIFF(year,[birthday], CAST('2021-09-09' as date)) , [birthday])) BETWEEN 1 AND 7 THEN 1
WHEN DATEDIFF(day, '2021-09-09', DATEADD(year, DATEDIFF(year,[birthday], CAST('2021-09-09' as date)) , [birthday])) BETWEEN 8 AND 31 THEN 2
ELSE 3
END
)
,[birthday]
FROM [info].[member] E
WHERE [system_active] = 1
) A
ORDER BY day ASC
For a better answer look at MatBailie's answer. This solution just worked for me