0
SELECT DISTINCT AppID,
                CASE
                  WHEN Category = '< 18 years old' THEN 'yes'
                  ELSE ''
                END AS '<18years old',
                CASE
                  WHEN Category = 'SSN Exists' THEN 'yes'
                  ELSE ''
                END AS 'Applicant has SSN',
                CASE
                  WHEN Category = 'Self Employed' THEN 'yes'
                  ELSE ''
                END AS 'Self employed'
FROM   Table1
WHERE  AppID = 123 

期望的输出 我正在尝试生成下面的结果,其中每个 AppID 只有 1 行,其中包含与其相关的所有信息。上面的代码为每个应用程序生成多行。我试图将 case 语句与 1 END 放在一起,但是当我在 END 关键字之前使用 Aliases 时出现错误。谢谢

AppID         <18 Year old           Applicant has SSN           Self employed  

123     yes         yes
124                 yes         yes
125                 yes         yes
4

4 回答 4

1

您需要 agroup by而不是 a distinct

SELECT AppID,
       max(CASE WHEN Category = '< 18 years old' THEN 'yes'
                ELSE ''
           END) AS '<18years old',
       max(CASE WHEN Category) = 'SSN Exists' THEN 'yes'
                ELSE ''
           END) AS 'Applicant has SSN',
       max(CASE WHEN Category = 'Self Employed' THEN 'yes'
                ELSE ''
           END) AS 'Self employed'
FROM   Table1
WHERE  AppID = 123
group by AppId
于 2012-11-29T16:45:00.100 回答
0

您可以按如下方式嵌套 Case 语句,并在末尾添加别名:

CASE WHEN 
    Category = '< 18 years old' 
THEN 'yes'
ELSE
    CASE WHEN
        Category = 'SSN Exists'
    THEN 'yes'
    ELSE
        ...
        ...
    END
END AS Alias

这就是你所追求的吗?

于 2012-11-29T16:42:53.880 回答
0

您的别名不应包含在“”中。

检查您的数据库引擎必须使用哪种类型的字符来包含别名。

于 2012-11-29T16:43:17.197 回答
0

如果我正确理解您的问题,您需要执行以下操作GROUP BY

SELECT  AppID,
        MAX(CASE
          WHEN Category = '< 18 years old' THEN 'yes'
          ELSE ''
        END) AS '<18years old',
        MAX(CASE
          WHEN Category = 'SSN Exists' THEN 'yes'
          ELSE ''
        END) AS 'Applicant has SSN',
        MAX(CASE
          WHEN Category = 'Self Employed' THEN 'yes'
          ELSE ''
        END) AS 'Self employed'
FROM   Table1
WHERE  AppID = 123 
GROUP BY AppID
于 2012-11-29T16:44:54.047 回答