Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple where clauses in one row sql

Tags:

sql

count

where

I want to take the below statement and fuse it into one query.

SELECT COUNT(*) AS count1 WHERE Month='11' AND Flag = 1
SELECT COUNT(*) AS count2 WHERE Month='11' AND Flag = 2
SELECT COUNT(*) AS count1 WHERE Month='12' AND Flag = 1
    SELECT COUNT(*) AS count2 WHERE Month='12' AND Flag = 2

I want this to display as one query with columns count1 and count2 and rows month 11 and month 12.

Is there a syntax for this?

like image 347
steventnorris Avatar asked Jun 06 '12 14:06

steventnorris


People also ask

Can you have more than one WHERE clause in SQL?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns.

Can WHERE clause have multiple values?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.

Can we use multiple columns in WHERE clause in SQL?

Show activity on this post. But the WHERE.. IN clause allows only 1 column.

Can we use WHERE GROUP BY together?

Absolutely. It will result in filtering the records on your date range and then grouping it by each day where there is data.


2 Answers

You can combine SUM and CASE to get various counts in one go:

SELECT
    Month,
    SUM(CASE WHEN Flag=1 THEN 1 ELSE 0 END) as count1,
    SUM(CASE WHEN Flag=2 THEN 1 ELSE 0 END) as count2
from
    ...
WHERE Month in ('11','12')
GROUP BY
    Month /* Other columns? */
like image 138
Damien_The_Unbeliever Avatar answered Dec 10 '22 09:12

Damien_The_Unbeliever


With two columns only, it can be something like this:

select
   (SELECT COUNT(*) FROM tablename WHERE Month='11' AND Flag = 1) as 'count1'
   (SELECT COUNT(*) FROM tablename WHERE Month='11' AND Flag = 2) as 'count2'

UNION ALL

select
   (SELECT COUNT(*) FROM tablename WHERE Month='12' AND Flag = 1), 
   (SELECT COUNT(*) FROM tablename WHERE Month='12' AND Flag = 2)

Replace tablename with the name of your table.

like image 28
aF. Avatar answered Dec 10 '22 11:12

aF.