2

我有一个 DB 表,其中的列以其他几列命名

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。

4

3 回答 3

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 

结果

| 颜色 | 计数 |
-----------------
| 绿色 | 3 |
| 红色 | 1 |

查看演示

于 2013-02-19T03:51:18.133 回答
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
于 2013-02-19T03:51:50.180 回答
0

这适用于 SQL Server、MySQL 和 PostgreSQL(SQLFiddle 演示):

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
于 2013-02-19T04:03:47.033 回答