I am working in SQL Server to generate some results. I have two columns, Auth
and DOB
and three conditions to consider:
The issue is since I am using DATE type for DOB, it's creating an issue for the the third condition since it is only in yyyy format.
This is the code that I am using
CASE
WHEN Auth IN ('Y', 'YES')
THEN CAST(REPLACE(DOB, '-', '') AS DATE)
WHEN Auth IN ('N', 'NO') AND DATEDIFF(YEAR, DOB@TODAY) <= 89
THEN YEAR(DOB)
WHEN Auth IN ('N', 'NO') AND DATEDIFF(YEAR, DOB@TODAY) > 89
THEN '1900'
ELSE ''
END AS BIRTHDATE
Can anyone please help me on how to do it with case itself?
Try this. It looks like you were getting a type clash in the second condition, which was returning an INT data type. Your statement said the second condition should return the DOB as is, which should be a VARCHAR data type to align with the other conditions of the CASE statement.
SELECT CASE
WHEN LEFT(Auth, 1) = 'Y' THEN FORMAT(DOB, 'yyMMdd')
WHEN LEFT(Auth, 1) = 'N'
AND DATEDIFF(YEAR, DOB, @TODAY) <= 89 THEN CAST(DOB AS VARCHAR)
WHEN LEFT(Auth, 1) = 'N'
AND DATEDIFF(YEAR, DOB, @TODAY) > 89 THEN '1900'
ELSE ''
END AS BIRTHDATE
FROM dbo.children AS c;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.