简体   繁体   English

在SQL Server中基于具有相同值的2列的值的总和或计数

[英]Sum or count of values based on 2 column with same values in SQL server

I have a DB table which has columns named with few more other columns 我有一个数据库表,其中包含以其他几个列命名的列

ColorA
ColorB
Status

The data in this DB look like this. 该数据库中的数据如下所示。

ColorA     ColorB    Status
---------     ---------    ---------
GREEN           NULL       YES
GREEN           NULL       YES
RED             GREEN      NO
RED             GREEN      YES

The result what I want is something like this depending on Status='YES' 我想要的结果是这样的,具体取决于Status ='YES'

Color  Count
GREEN   3
RED     1

I have also defined table which hold all the color. 我还定义了包含所有颜色的表格。

How to construct the SQL query for this which will result in the output as mentioned earlier? 如何为此构造SQL查询,这将导致前面提到的输出? I have a query but I am using LEFT Join and then doing an UNION which is not giving proper result. 我有一个查询,但我使用的是LEFT Join,然后执行未给出正确结果的UNION。

This should work: 这应该工作:

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 

Result 结果

| COLOR | COUNT |
-----------------
| GREEN |     3 |
|   RED |     1 |

See the demo 观看演示

From the example you have given you want to know the count of each ColorA or ColorB record 从您给出的示例中,您想知道每个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

This works in SQL Server, MySQL and PostgreSQL ( SQLFiddle demo ): 这适用于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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM