$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如何处理()中的多个列。
答案 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
计算所有非空值
表达式产生一个布尔值,可以是TRUE
,FALSE
或NULL
您只想计算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;