开发者

Merge two SELECT queries into one

I have two queries where I only need the count of total records but the only difference开发者_Python百科 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


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')


select  sum(case when category = 'value_a' then 1 else 0 end) group_a,
        sum(case when category = 'value_b' then 1 else 0 end) group_b
from tbl


SELECT category,COUNT(*) FROM tbl
GROUP BY category;

That expands to more categories. If you want just those categories

SELECT category,COUNT(*) FROM tbl
WHERE category IN ('value_a', 'value_b')
GROUP BY category; 


What strange answers for counting. Here's a straightforward COUNT:

SELECT COUNT(category = 'value_a' OR NULL) AS group_a, COUNT(category = 'value_b' OR NULL) AS group_b FROM tbl;

The COUNT aggregate in PostgreSQL allows complex syntax like I've shown. Note that the OR NULL is quite essential as COUNT counts only those rows for which the condition category = '...' OR NULL gives non-NULL answer.


Just for the fun of it:

SELECT * 
FROM 
(
    SELECT category
    FROM tbl 
) subquery
PIVOT
(
    COUNT(category)
    FOR category IN ([value_a],[value_b])
) AS piv
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜