在POSTGRES中每行返回COUNT而不是总和或单行

时间:2011-07-25 15:13:45

标签: sql postgresql select count

我使用过这方面的变体:

SELECT (select count(active) AS true 
        from sooper_entry 
        where active = 't' 
        and entry_id_ref = 28) AS true,
       (select count(active) AS false 
        from sooper_entry 
        where active = 'f' 
        and entry_id_ref = 28) AS false;

所以我可以获得所有true和false的COUNT,但我需要在关联数组中返回一个真正的错误计数。

期望的结果:

 true | false | uId 
------+-------+-----
   16 |     0 |  1
   10 |     2 |  3
   13 |    10 |  4
   19 |     8 |  5
   12 |     3 |  8
   21 |     0 | 12
(6 rows)

2 个答案:

答案 0 :(得分:4)

SELECT 
  sum(case when active = 't' then 1 else 0 end) AS true, 
  sum(case when active = 'f' then 1 else 0 end) AS false, 
  entry_id_ref
FROM sooper_entry
GROUP BY entry_id_ref

答案 1 :(得分:1)

SELECT  SUM(active::BOOLEAN::INT) AS active, 
        SUM((NOT active::BOOLEAN)::INT) AS inactive, 
        entry_id_ref
FROM    sooper_entry
GROUP BY
        entry_id_ref