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
OUTPUT Desired 我正在尝试生成下面的结果,其中每个AppID只有1行 所有与之相关的信息。上面的代码产生多行 为每个应用程序。我试图将case语句与1 END结合在一起, 但是当我在END关键字之前使用别名时出现错误。感谢
AppID <18 Year old Applicant has SSN Self employed
123 yes yes
124 yes yes
125 yes yes
答案 0 :(得分:1)
您需要group by
而不是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
答案 1 :(得分:0)
您可以按如下方式嵌套Case语句,最后只是别名:
CASE WHEN
Category = '< 18 years old'
THEN 'yes'
ELSE
CASE WHEN
Category = 'SSN Exists'
THEN 'yes'
ELSE
...
...
END
END AS Alias
这就是你要追求的吗?
答案 2 :(得分:0)
您的别名不应包含在''。
中检查数据库引擎必须使用哪种字符来封装别名。
答案 3 :(得分: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