问题:如何使用case语句对表进行分组。
例如,我有两张桌子。第一张表
id name
1 a
2 b
3 c
第二张表是
身份证明状态
1红色
1红色
1蓝色
1红色
这是情景:
如果它具有相同的id,那么它将创建一个case语句。
我将如何创建这个?
答案 0 :(得分:1)
对于大多数/所有DBMS的一般方法,您可以使用:
SELECT t.ID,
t.Name,
CASE WHEN t.Red = t.Total THEN 'Only Red condition'
WHEN t.Red > 0 AND t.Blue > 0 THEN 'Red and blue condition'
ELSE 'Other condition'
END AS CaseCondition
FROM ( SELECT Table1.ID,
Table1.Name,
COUNT(CASE WHEN Table2.Status = 'Red' THEN 1 END) AS Red,
COUNT(CASE WHEN Table2.Status = 'Blue' THEN 1 END) AS Blue,
COUNT(Table2.Status) AS Total
FROM Table1
LEFT JOIN Table2
ON Table1.ID = Table2.ID
GROUP BY Table1.ID, Table1.Name
) t
如果您的DBMS支持PIVOT(并且唯一可能的值是红色和蓝色),那么您可以使用以下内容:
SELECT ID,
Name
CASE WHEN pvt.Red > 0 AND pvt.Blue = 0 THEN 'Only Red condition'
WHEN t.Red > 0 AND t.Blue > 0 THEN 'Red and blue condition'
ELSE 'Other condition'
END AS CaseCondition
FROM Table1
LEFT JOIN Table2
ON Table1.ID = Table2.ID
PIVOT
( COUNT(Table2.ID)
FOR Table2.Status IN ([Red], [Blue])
) pvt