如何计算SQL中特定字段的比例?

时间:2015-10-09 20:12:28

标签: sql postgresql

假设我有一个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中不起作用。有什么想法吗?

感谢

3 个答案:

答案 0 :(得分:3)

pip

答案 1 :(得分:1)

我认为您必须使用CASE代替IF

SQL Fiddle Demo

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'