postgreSQL查询 - 计算在两列上匹配的列值

时间:2011-01-14 11:45:45

标签: sql postgresql

我需要帮助创建一个SQL查询来计算在两个不同列上分开的行。

这是我的桌子的DDL:

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)
);

表中的样本数据

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。

我需要单独计算('new','regular','gold')。这是我想要的输出:

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

2 个答案:

答案 0 :(得分:19)

几周前,我一直在努力 这就是你需要的。

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;

答案 1 :(得分: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