Lets say I have a table that has 50 Fields. 20 of those fields can contain the Value "YES" "NO" or "N/A". How do I query the number of "YES"s for a given row?
SQL Count Function: If we define a column in the COUNT statement: COUNT ([column_name]), we count the number of rows with non-NULL values in that column. We can specify to count only unique values by adding the DISTINCT keyword to the statement.
COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.
You write a long statement that adds up the values:
select ((case when value1 = 'Yes' then 1 else 0 end) +
(case when value2 = 'Yes' then 1 else 0 end) +
. . .
(case when value50 = 'Yes' then 1 else 0 end)
) as NumYesses
This would be much easier if you normalized the data, so each value was in a separate row. You would do this by having a separate table, called a junction or association table.
Also, you can generate this code in a spreadsheet, such as Excel, by using formulas on the columns names (or by writing a query that uses metadata in your database).
Note: this is generic ANSI SQL, because you don't specify the database. There may be some shortcuts to writing the code in different databases.
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