假设我有一个SQL表data
为
ID Date Action Params
A 20151001 Foo 1
A 20151002 Foo 2
A 20151001 Bar 10
B 20151001 Foo 0
B 20151002 Foo 0
B 20151003 Bar 1
在单个查询中,给定特定ID,我想计算具有操作Foo
的条目的比例。例如,给定A,3个动作中有2个Foo
个。所以它是66%。
我想要这样的东西
SELECT SUM(IF action = 'Foo', 1, 0)*100 / count(*)
FROM data
WHERE ID='A'
但是IF
在postgres中不起作用。有什么想法吗?
感谢
答案 0 :(得分:3)
pip
答案 1 :(得分:1)
我认为您必须使用CASE
代替IF
SELECT SUM(CASE
WHEN "Action" = 'Foo' THEN 1
ELSE 0
END)*100 / count(*)
FROM data
WHERE "ID"='A'
group by "ID"
您可能需要使用分析功能的附加奖励
SELECT
"ID",
"Action",
COUNT(*) OVER (PARTITION BY "ID", "Action" ORDER BY "ID") as aTotal,
COUNT(*) OVER (PARTITION BY "ID" ORDER BY "ID") as bTotal
From data;
答案 2 :(得分:0)
Case
是不必要的:
select sum((action = 'Foo')::int)* 100/ count(*)
from data
where id = 'A'