简体   繁体   中英

Count how many columns have a specific value

I have a table that looks like this:

ID    x1    x2    x3    x4
1     20    30    0     0
2     60    0     0     0
3     10    30    0     0
4     30    30    30    30

I want to be able to query this and return the ID with the number of columns that have more than 0 as their value in that row. So the result would look like this:

ID    Count
1     2
2     1
3     2
4     4

Try this:

Select 
    ID,
    Case When x1 <> 0 Then 1 Else 0 End + 
    Case When x2 <> 0 Then 1 Else 0 End + 
    Case When x3 <> 0 Then 1 Else 0 End + 
    Case When x4 <> 0 Then 1 Else 0 End as Count
From MyTable

While this is easy to code, the more columns you have, the larger your select is going to be the more columns you will have to add.

Try this:

SELECT ID, z.cnt
FROM mytable
CROSS APPLY (SELECT COUNT(*) AS cnt 
             FROM (VALUES (x1), (x2), (x3), (x4)) x(y)
             WHERE x.y > 0) z

This query makes use of a Table Value Constructor to create an in-line table whose rows are the columns of the initial table. Performing a COUNT on this in-line table, you can get the number of columns greater than zero.

I think this scales well if you have more than 4 columns.

Demo here

This should do what you need if you have a fixed set of columns known at design time :

 SELECT ID,
        IIF (x1 > 0, 1, 0) + 
        IIF (x2 > 0, 1, 0) + 
        IIF (x3 > 0, 1, 0) + 
        IIF (x4 > 0, 1, 0) 
 FROM MyTable

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