Postgresql查询COUNT和MAX在一起?

时间:2012-04-18 13:50:49

标签: postgresql

SELECT id,icon,type,cnt 
FROM  capability 
JOIN (
    SELECT s0_.capability_id AS capability_id0 ,
           count(capability_id) as cnt  
    FROM service_offer_capability s0_ 
    INNER JOIN service_offer s1_ ON s0_.service_offer_id = s1_.id 
    WHERE s0_.value <> 'i:0;' AND s1_.service_id = 2 
    GROUP BY s0_.capability_id
) af
ON af.capability_id0=id;

我想做的就是将max(cnt)作为额外的列。我知道您可以通过cnt订购并获得第一个但我正在寻找替代方案..是否可能或我必须运行多个查询?

1 个答案:

答案 0 :(得分:3)

这应该这样做:

SELECT id,
       icon,
       type,
       cnt,
       max(cnt) over () as max_cnt
FROM  capability 
JOIN (
    SELECT s0_.capability_id AS capability_id0 ,
           count(capability_id) as cnt  
    FROM service_offer_capability s0_ 
    INNER JOIN service_offer s1_ ON s0_.service_offer_id = s1_.id 
    WHERE s0_.value <> 'i:0;' AND s1_.service_id = 2 
    GROUP BY s0_.capability_id
) af
ON af.capability_id0=id;