Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count how many columns have a specific value

Tags:

sql

sql-server

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
like image 681
rottenbanana Avatar asked Dec 19 '22 01:12

rottenbanana


2 Answers

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

like image 80
Giorgos Betsos Avatar answered Dec 21 '22 13:12

Giorgos Betsos


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.

like image 30
Raj More Avatar answered Dec 21 '22 14:12

Raj More