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:

MALESFEMALES
10004 20421

The conditions in the case statement can be a lot more complex and can include sub-queries.

posted @ 2013-10-24 13:47  Bryan chen  阅读(154)  评论(0编辑  收藏  举报