获得两种不同条件的计数

时间:2013-04-18 13:01:09

标签: sql postgresql

假设我有一个表states,如下所示:

create table states (id int4 unique not null, state int4 not null);

我想获取表中状态为1的行数,以及表中状态为2的行数。在两个单独的查询中执行此操作非常简单:

select count(*) from states where state = 1;
select count(*) from states where state = 2;

但两次完整的表格似乎很愚蠢。有人会想到一些聪明的技巧,这些技巧可以让我在一个陈述中获得相同的信息并只通过一次表吗?

4 个答案:

答案 0 :(得分:5)

select
    count((state = 1)::integer or null) state_1,
    count((state = 2)::integer or null) state_2
from states

select
    sum((state = 1)::integer) state_1,
    sum((state = 2)::integer) state_2
from states

答案 1 :(得分:5)

您可以使用具有聚合函数的CASE

select
  sum(case when state=1 then 1 else 0 end) State1,
  sum(case when state=2 then 1 else 0 end) State2
from states

答案 2 :(得分:1)

SELECT [state], COUNT(*) TotalRows 
FROM [Expense].[dbo].[state]
GROUP BY [state]

假设您使用的是SQL Server

答案 3 :(得分:1)

select count(*) from states group by state having state = 1 or state=2;

使用SQL group by