Conditional Counting In SQL
If you ever want to conditionally count the number of times a particular condition occurs in SQL, you can do it in Oracle using the case andcount functions. Here's a simple example which counts the number of males/females stored in PS_PERSONAL_DATA. select count(case when SEX = 'M' then 1 end) as MALES, count(case when SEX = 'F' then 1 end) asFEMALESfrom PS_PERSONAL_DATA
All that is happening is that the case statement returns a 1 for every instance where the gender is M or F and the count, counts each returned value of 1 giving a summary like this:
The conditions in the case statement can be a lot more complex and can include sub-queries. |