我有一个样本数据集如下:
TOPIC STATUS
Physics C
Maths I
Chemistry C
Chemistry I
Chemistry I
Maths C
Maths C
Physics I
Physics C
Maths C
如何获得TOPIC
的完成次数与下面的总次数相比?
百分比公式为100 *(C总数/发生总数)
TOPIC PERCENT
Physics 66.66
Maths 75
Chemistry 33.33
通常我会编写子查询来获取这个,如果在T-SQL中(我已经熟悉)。
但是,我是postgreSQL的新手,在我编写相同的子查询之前,只想检查是否有一种有效的方法在postgreSQL中获取它。
按要求更新
我使用下面的T-SQL代码得到了预期的结果,但是正在寻找一种使用psql的有效方法
IF OBJECT_ID('tempDB..##SOO',N'U') IS NOT NULL
DROP TABLE ##SOO
GO
SELECT * INTO ##SOO FROM(
SELECT 'PHYSICS' [TOPIC],'C' [STATUS]
UNION ALL
SELECT 'PHYSICS' [TOPIC],'C' [STATUS]
UNION ALL
SELECT 'PHYSICS' [TOPIC],'I' [STATUS]
UNION ALL
SELECT 'MATHS' [TOPIC],'C' [STATUS]
UNION ALL
SELECT 'MATHS' [TOPIC],'C' [STATUS]
UNION ALL
SELECT 'MATHS' [TOPIC],'I' [STATUS]
UNION ALL
SELECT 'MATHS' [TOPIC],'C' [STATUS]
UNION ALL
SELECT 'CHEMISTRY' [TOPIC],'I' [STATUS]
UNION ALL
SELECT 'CHEMISTRY' [TOPIC],'I' [STATUS]
UNION ALL
SELECT 'CHEMISTRY' [TOPIC],'C' [STATUS]
)A
GO
SELECT S.TOPIC, 100*S.PASS/S.KNT [PERCENTO] FROM(
SELECT A.TOPIC,A.KNT,B.PASS FROM(
SELECT TOPIC, COUNT(1) [KNT] FROM ##SOO
GROUP BY TOPIC)A
JOIN
(SELECT TOPIC, COUNT(1) [PASS] FROM ##SOO
WHERE [STATUS] ='C'
GROUP BY TOPIC)B ON A.TOPIC=B.TOPIC
)S
答案 0 :(得分:0)
如果您更改这些标识符以符合标准SQL,那么该查询在Postgres中应该可以正常工作。
然而,它确实可以在Postgres(和SQL Server)中简化:
select topic,
(count(*) filter (where status = 'C'))::numeric / count(*) as pct
from soo
group by topic;
请注意,如果使用filter()
表达式替换case
子句,上述内容也适用于SQL Server:
select topic,
(count(case when status = 'C' then 1 end))::numeric / count(*) as pct
from soo
group by topic;