简体   繁体   中英

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'

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? I have a query but I am using LEFT Join and then doing an UNION which is not giving proper result.

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

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 ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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