我有两个查询,我只需要总记录数,但查询中唯一的区别是一个字段值。
实施例
SELECT COUNT(*) AS group_a
FROM tbl
WHERE category = 'value_a'
SELECT COUNT(*) AS group_b
FROM tbl
WHERE category = 'value_b'
我怎样才能得到这样的东西:(伪)
SELECT COUNT(*) AS group_a, COUNT(*) AS group_b
FROM tbl
WHERE category IN ('value_a', 'value_b')
但结果是这样的
group_a , group_b
56, 101
我在查询中想一个CASE语句来过滤这两个但是我该如何实现呢?还是有更好的方法?
我现在正在做一个UNION,但想知道我是否可以返回一条有两个结果的记录
答案 0 :(得分:6)
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')
答案 1 :(得分:2)
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
答案 2 :(得分:2)
SELECT category,COUNT(*) FROM tbl
GROUP BY category;
扩展到更多类别。如果你只想要那些类别
SELECT category,COUNT(*) FROM tbl
WHERE category IN ('value_a', 'value_b')
GROUP BY category;
答案 3 :(得分:2)
计数有什么奇怪的答案。这是一个简单的COUNT:
SELECT COUNT(category = 'value_a' OR NULL) AS group_a, COUNT(category = 'value_b' OR NULL) AS group_b FROM tbl;
PostgreSQL中的COUNT聚合允许像我所示的复杂语法。请注意,OR NULL
非常重要,因为COUNT仅计算条件category = '...' OR NULL
给出非NULL答案的行。
答案 4 :(得分:1)
只为了它的乐趣:
SELECT *
FROM
(
SELECT category
FROM tbl
) subquery
PIVOT
(
COUNT(category)
FOR category IN ([value_a],[value_b])
) AS piv