3

假设我有一个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

4 回答 4

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
于 2013-04-18T13:03:34.663 回答
5

您可以将 aCASE与聚合函数一起使用:

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
于 2013-04-18T13:03:52.523 回答
1
SELECT [state], COUNT(*) TotalRows 
FROM [Expense].[dbo].[state]
GROUP BY [state]

假设您使用的是 SQL Server

于 2013-04-18T13:22:39.827 回答
1
select count(*) from states group by state having state = 1 or state=2;

使用 SQL 分组方式

于 2013-04-18T13:28:14.387 回答