我有一个数据库表,其中的列名称中包含更多其他列
ColorA
ColorB
Status
此数据库中的数据如下所示。
ColorA ColorB Status
--------- --------- ---------
GREEN NULL YES
GREEN NULL YES
RED GREEN NO
RED GREEN YES
我想要的结果是这样的,取决于Status ='YES'
Color Count
GREEN 3
RED 1
我还定义了包含所有颜色的表。
如何为此构造SQL查询,这将导致前面提到的输出?我有一个查询,但我正在使用LEFT Join然后做一个没有给出正确结果的UNION。
答案 0 :(得分:4)
这应该有效:
SELECT a.color,
Count(a.color) AS Count
FROM (SELECT colora AS color
FROM table1
WHERE status = 'YES'
AND colora IS NOT NULL
UNION ALL
SELECT colorb
FROM table1
WHERE status = 'YES'
AND colorb IS NOT NULL) a
GROUP BY a.color
<强>结果强>
| COLOR | COUNT | ----------------- | GREEN | 3 | | RED | 1 |
答案 1 :(得分:0)
从您给出的示例中,您想知道每个ColorA或ColorB记录的计数
SELECT Color, SUM(Total) AS Count
FROM (
SELECT ColorA as Color, SUM(CASE WHEN Status = 'Yes' THEN 1 ELSE 0 END) AS Total
Group By ColorA
UNION
SELECT ColorB as Color, SUM(CASE WHEN Status = 'Yes' THEN 1 ELSE 0 END) AS Total
Group By ColorB
) U
GROUP BY Color
答案 2 :(得分:0)
这适用于SQL Server,MySQL和PostgreSQL(SQLFiddle demo):
SELECT color, sum(cnt) AS count FROM (
SELECT colorA AS color, count(*) AS cnt
FROM mytable
WHERE status = 'YES'
GROUP BY colorA
UNION ALL
SELECT colorB AS color, count(*) AS cnt
FROM mytable
WHERE status = 'YES'
GROUP BY colorB
) AS x
WHERE color IS NOT NULL
GROUP BY color