简体   繁体   English

SQL 服务器中的CASE 多条件

[英]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:我有两列, AuthDOB以及要考虑的三个条件:

  1. Auth has Y then DOB will have date pf birth without any special character in the format yyyymmdd Auth 有 Y,然后 DOB 将有日期 pf 出生,没有任何特殊字符,格式为 yyyymmdd
  2. Auth has N and the age is less than or equal to 89 then we enter the DOB Auth有N且年龄小于等于89然后我们进入DOB
  3. Auth has N and the age is more than 89 then we just enter the year 1900 Auth 有 N 且年龄超过 89 岁那么我们就进入 1900 年

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM