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, 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With