为什么这两个计数返回相同的数字?

时间:2012-12-21 17:54:03

标签: php postgresql count

$SQL = "SELECT pc.dist_id, pc.route, pc.types,
        COUNT( pc.types = '$type' ) total,
        COUNT( pc.types = '$type' AND pc.options = '1') callbacks

        FROM per_call pc
        WHERE pc.types = '$type'
        GROUP BY pc.dist_id, pc.route, pc.types
        ORDER BY pc.dist_id, pc.route";

简而言之,我想我是在问COUNT如何处理()中的多个列。

2 个答案:

答案 0 :(得分:2)

Count也可以使用:

SELECT pc.dist_id, pc.route, pc.types,
COUNT( CASE WHEN pc.types = '$type' THEN 1 END) total,
COUNT( CASE WHEN pc.types = '$type' AND pc.options = '1' THEN 1 END) callbacks

FROM per_call pc
WHERE pc.types = '$type'
GROUP BY pc.dist_id, pc.route, pc.types
ORDER BY pc.dist_id, pc.route

注意:它有效,因为COUNT返回非NULL值的数量,而CASE具有默认ELSE NULL ...

答案 1 :(得分:1)

另一个略短的变体(性能与CASE语句大致相同):

SELECT pc.dist_id, pc.route, pc.types
      ,COUNT(NULLIF(pc.types = '$type', FALSE) AS total
      ,COUNT(NULLIF(pc.types = '$type' AND pc.options = '1', FALSE) AS callbacks
FROM   per_call pc
WHERE  pc.types = '$type'
GROUP  BY pc.dist_id, pc.route, pc.types
ORDER  BY pc.dist_id, pc.route;

背后的主要是: COUNT计算所有非空值 表达式产生一个布尔值,可以是TRUEFALSENULL 您只想计算TRUE案例 因此,将FALSE转换为NULL,一切都很常规。

或者,甚至更短,但不是更快:

SELECT pc.dist_id, pc.route, pc.types
      ,sum((pc.types = '$type')::int) AS total
      ,sum((pc.types = '$type' AND pc.options = '1')::int) AS callbacks
FROM   per_call pc
WHERE  pc.types = '$type'
GROUP  BY pc.dist_id, pc.route, pc.types
ORDER  BY pc.dist_id, pc.route;

boolean强制转换为integer,将TRUE转换为1,将FALSE转换为0.因此,sum()有效。

由于您的pc.types = '$type'条件为WHERE,因此您可以简化为:

SELECT pc.dist_id, pc.route, pc.types
      ,COUNT(*) AS total  -- slightly faster, too
      ,COUNT(NULLIF(pc.options = '1', FALSE) AS callbacks
FROM   per_call pc
WHERE  pc.types = '$type'
GROUP  BY pc.dist_id, pc.route, pc.types
ORDER  BY pc.dist_id, pc.route;