我需要帮助创建一个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)
);
Run Code Online (Sandbox Code Playgroud)
表格中的样本数据
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
Run Code Online (Sandbox Code Playgroud)
我想按城市计算新客户,常客和gold_customers.
我需要单独计算('new','regular','gold').这是我想要的输出:
'city' |new_customers|regular_customers|gold_customers
'Moscow' |1 |1 |1
'Beijing'|1 |2 |0
'London' |1 |1 |0
Run Code Online (Sandbox Code Playgroud)
ath*_*spk 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;
Run Code Online (Sandbox Code Playgroud)
您可以分组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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6297 次 |
| 最近记录: |