Domanda

I have a table in postgres with 10 fields, and need to check for certain values in 3 of them, then return the field name which met the condition and the number of rows in each field.

So it's something like:

select count(*)
from table
where field1 ilike '%E+%'
OR field2 ilike '%E+%'
OR field3 ilike '%E+%'

and then return the field which met the condition AND the number of rows (which I'm not sure how to do it)

È stato utile?

Soluzione

you can use conditional aggregation for that:

select count(*), 
       count(*) filter (where field1 ilike '%E+%') as field1_matches,
       count(*) filter (where field2 ilike '%E+%') as field2_matches,
       count(*) filter (where field3 ilike '%E+%') as field3_matches
from the_table
where field1 ilike '%E+%'
   OR field2 ilike '%E+%'
   OR field3 ilike '%E+%'
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a dba.stackexchange
scroll top