3

次のようなテーブルがあるstatesとします。

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

状態が 1 のテーブルの行数と、状態が 2 のテーブルの行数を取得したいと考えています。これを 2 つの別々のクエリで行うのは簡単です。

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

しかし、テーブル全体を 2 回調べるのはばかげているようです。誰かが、1 つのステートメントで同じ情報を取得し、テーブルを 1 回だけ通過できる巧妙なトリックを思いつくことができますか?

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

CASE集計関数でa を使用できます。

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 サーバーを使用しているとします。

于 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 に答える