Is there a way to get multiple counts depending on multiple conditions from the same table? eg. Count for when Days is less than 15, and count for days between 15 and 30.
+9
A:
Yes, you can combine SUM and CASE:
SELECT
SUM(CASE WHEN condition1 THEN 1 ELSE 0 END) count1,
SUM(CASE WHEN condition2 THEN 1 ELSE 0 END) count2
FROM yourtable
So for your specific example:
SELECT
SUM(CASE WHEN days < 15 THEN 1 ELSE 0 END) count1,
SUM(CASE WHEN days BETWEEN 15 AND 30 THEN 1 ELSE 0 END) count2
FROM yourtable
If the majority of rows have days > 30
it might be worth adding a WHERE days <= 30
to the end of the query as an optimization. Also be aware that BETWEEN includes both its end points.
Mark Byers
2010-06-28 09:44:39
Worked like a charm. Thank you for your help.
Rabin
2010-06-28 09:51:03