Reputation: 2608
Suppose I have a table states
as follows:
create table states (id int4 unique not null, state int4 not null);
I want to get the number of rows in the table that whose state is 1, and the number of rows in the table whose state is 2. Doing this in two separate queries is straightforward:
select count(*) from states where state = 1;
select count(*) from states where state = 2;
But it seems silly to go through the whole table twice. Can someone think of some clever trick that would allow me to get the same information in a single statement and going through the table only once?
Upvotes: 3
Views: 110
Reputation: 11
SELECT [state], COUNT(*) TotalRows
FROM [Expense].[dbo].[state]
GROUP BY [state]
Assume you are using SQL server
Upvotes: 1
Reputation: 485
select count(*) from states group by state having state = 1 or state=2;
Use SQL group by
Upvotes: 1
Reputation: 247650
You can use a CASE
with an aggregate function:
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
Upvotes: 5
Reputation: 125214
select
count((state = 1)::integer or null) state_1,
count((state = 2)::integer or null) state_2
from states
or
select
sum((state = 1)::integer) state_1,
sum((state = 2)::integer) state_2
from states
Upvotes: 5