对于每个国家/地区,输出其代码以及以下有关其艺术家的信息(按给定顺序): 乐队数量,非乐队艺术家数量,艺术家总数,乐队百分比,非乐队艺术家百分比。没有艺术家的国家不会出现在输出中。将百分比格式设置为带有0个小数位的十进制数字。
数据格式:
艺术家
-名称(字符串)
-类型(人或乐队)
-国家(唯一的3位数字代码)
国家/地区
-代码(唯一的3位数字代码)
-名称(字符串)
示例: 艺术家
Name | Type | Country
-----------------------
John Band qwe
Doe Band qwe
Mary Person qwe
Anon Person asd
国家/地区
Code | Name
--------------
qwe Russia
asd New Zealand
预期输出:
Code | # of bands | # of artists not in band | total # of artists | % of bands | % of artists not in bands
-----------------------------------------------------------------------------------------------------------
qwe 2 1 3 66 33
asd 0 1 1 0 100
我只是不知道如何跟踪所有内容,而本质上却喜欢保存它们,因此我可以一次输出所有它们。如果一次仅一个国家/地区,我想我会得到的,但是如果其中有多个国家/地区,那我就迷失了。
有关如何执行此操作的任何资源?
谢谢
答案 0 :(得分:1)
您可以尝试在CTE
中使用条件汇总函数,然后在主查询中进行计算。
模式(PostgreSQL v9.6)
CREATE TABLE Artists(
Name VARCHAR(50),
Type VARCHAR(50),
Country VARCHAR(50)
);
INSERT INTO Artists VALUES ('John','Band','qwe');
INSERT INTO Artists VALUES ('Doe','Band','qwe');
INSERT INTO Artists VALUES ('Mary','Person','qwe');
INSERT INTO Artists VALUES ('Anon','Person','asd');
CREATE TABLE Countries(
Code VARCHAR(50),
Name VARCHAR(50)
);
INSERT INTO Countries VALUES ('qwe','Russia');
INSERT INTO Countries VALUES ('asd','New Zealand');
查询#1
WITH CTE AS (
SELECT Code,
COUNT(CASE WHEN Type ='Band' THEN 1 END) BandCnt,
COUNT(CASE WHEN Type <> 'Band' THEN 1 END) NotBandCnt,
COUNT(Country) CountryCnt
FROM Artists a
join Countries c on a.Country = c.Code
GROUP BY Code
)
SELECT Code,
BandCnt "# of bands",
NotBandCnt "# of artists not in band",
CountryCnt "total # of artists",
BandCnt * 100.0 / CountryCnt "% of bands",
notBandCnt * 100.0 / CountryCnt "% of artists not in band"
FROM CTE;
结果
| code | # of bands | # of artists not in band | total # of artists | % of bands | % of artists not in band |
| ---- | ---------- | ------------------------ | ------------------ | ---------------------- | ------------------------ |
| asd | 0 | 1 | 1 | 0.00000000000000000000 | 100.0000000000000000 |
| qwe | 2 | 1 | 3 | 66.6666666666666667 | 33.3333333333333333 |