[英]CASE in SQL Server with multiple conditions
I am working in SQL Server to generate some results.我在 SQL 服务器上工作以生成一些结果。 I have two columns, Auth
and DOB
and three conditions to consider:我有两列, Auth
和DOB
以及要考虑的三个条件:
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.问题是因为我对 DOB 使用 DATE 类型,所以它为第三个条件创建了一个问题,因为它只是 yyyy 格式。
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.看起来您在第二个条件中遇到了类型冲突,即返回 INT 数据类型。 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.您的语句说第二个条件应该按原样返回 DOB,它应该是 VARCHAR 数据类型以与 CASE 语句的其他条件保持一致。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.