Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two SELECT queries into one

I have two queries where I only need the count of total records but the only difference in the queries is one field value.

Example;

SELECT COUNT(*) AS group_a
FROM tbl
WHERE category = 'value_a'

SELECT COUNT(*) AS group_b
FROM tbl
WHERE category = 'value_b'

How can I get something like this: (pseudo)

SELECT COUNT(*) AS group_a, COUNT(*) AS group_b
FROM tbl
WHERE category IN ('value_a', 'value_b')

But the results are like this

group_a , group_b
56, 101

I was thinking a CASE statement in the query to filter the two but how do I implement it? or is there a better way?

I'm doing a UNION right now but wanted to know if I could return one record with two results

like image 775
Phill Pafford Avatar asked Feb 23 '11 14:02

Phill Pafford


1 Answers

select sum(case when category = 'value_a' then 1 else 0 end) as group_a,
       sum(case when category = 'value_b' then 1 else 0 end) as group_b
    from tbl
    where category in ('value_a', 'value_b')
like image 184
Joe Stefanelli Avatar answered Oct 13 '22 12:10

Joe Stefanelli