2011-01-14 86 views
15

我需要幫助創建一個SQL查詢來計算在兩個單獨列上劃分的行。postgreSQL查詢 - 計算兩列上匹配的列值

這是DDL爲我的表:從表

AGENCY 
id|'city' 
1 |'London' 
2 |'Moscow' 
3 |'Beijing' 

CUSTOMER 
id|'fullname'  |'status' |agencyid 
1 |'Michael Smith' |'new' |1 
2 |'John Doe'  |'regular'|1 
3 |'Vlad Atanasov' |'new' |2 
4 |'Vasili Karasev'|'regular'|2 
5 |'Elena Miskova' |'gold' |2 
6 |'Kim Yin Lu' |'new' |3 
7 |'Hu Jintao'  |'regular'|3 
8 |'Wen Jiabao' |'regular'|3 

我想通過城市來計算新客戶,常客和gold_customers

CREATE TABLE Agency (
    id SERIAL not null, 
    city VARCHAR(200) not null, 
    PRIMARY KEY(id) 
); 
CREATE TABLE Customer (
    id SERIAL not null, 
    fullname VARCHAR(200) not null, 
    status VARCHAR(15) not null CHECK(status IN ('new','regular','gold')), 
    agencyID INTEGER not null REFERENCES Agency(id), 
    PRIMARY KEY(id) 
); 

樣本數據。 ('new','regular','gold')需要單獨計算。這裏是我想要的輸出:

'city' |new_customers|regular_customers|gold_customers 
'Moscow' |1   |1    |1 
'Beijing'|1   |2    |0 
'London' |1   |1    |0 
+1

的可能重複[T-SQL:是有可能指定數條件()?] (http://stackoverflow.com/questions/1400078/t-sql-is-it-possible-to-specify-condition-in-count) – Guffa 2011-01-14 11:52:37

+5

+1 SQL DDL :) – onedaywhen 2011-01-14 12:14:22

回答

18

幾周前我一直在掙扎。
這就是你需要的。

SELECT 
    Agency.city, 
    count(case when Customer.status = 'new' then 1 else null end) as New_Customers, 
    count(case when Customer.status = 'regular' then 1 else null end) as Regular_Customers, 
    count(case when Customer.status = 'gold' then 1 else null end) as Gold_Customers 
FROM 
    Agency, Customer 
WHERE 
    Agency.id = Customer.agencyID 
GROUP BY 
    Agency.city; 
+0

謝謝你!工作正常 – openV 2011-01-14 11:57:59

6

,你可以在city組,然後總結在每個城市狀態的數量:

select city 
,  sum(case when c.status = 'new' then 1 end) as New 
,  sum(case when c.status = 'regular' then 1 end) as Regular 
,  sum(case when c.status = 'gold' then 1 end) as Gold 
from customer c 
join agency a 
on  c.agencyid = a.id 
group by 
     a.city