SQL How to count the number of specific values ​​in a row

Let's say I have a table with 50 fields. 20 of these fields may contain β€œYES”, β€œNO” or β€œN / A”. How to request the quantity "YES" for a given string?

+6
source share
1 answer

You write a long statement that adds 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 

It would be much easier if you normalized the data, so each value was on a separate line. You would do this with a separate table called a join or association table.

Alternatively, you can generate this code in a spreadsheet such as Excel, using formulas in column names (or by writing a query that uses metadata in your database).

Note: this is generic ANSI SQL because you are not specifying a database. There may be several shortcuts for writing code in different databases.

+7
source

Source: https://habr.com/ru/post/973757/


All Articles