COUNT中的条件子句

时间:2014-10-30 13:40:47

标签: sql postgresql

我的请求中有问题:

SELECT regionn, COUNT(regionn) AS total,
COUNT(last_date_o) AS ouvreurs,
COUNT(last_date_o)*100/COUNT(regionn) AS ratio,
COUNT(gender='mr'), COUNT(gender='mme')
FROM data WHERE length(regionn)=2
GROUP BY regionn ORDER BY regionn ASC

性别列有两个可能的值:' mr'或者' mme'。 使用COUNT(性别=' mr'),COUNT(性别=' mme')我想要每个的总数,但返回相同的值。

事实上COUNT(性别=' mr'),COUNT(性别=' mme')与COUNT(性别),COUNT(性别)......完全相同/ p>

我该怎么做?

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

COUNT不是正确的聚合器,您应该使用SUM

  

实际上COUNT(gender='mr')COUNT(gender='mme')COUNT(gender)完全相同

这是因为COUNT计算了不是NULL的任何内容,而SUM会将1和0加起来。

SELECT
    regionn
,   COUNT(regionn) AS total
,   COUNT(last_date_o) AS ouvreurs\
,   COUNT(last_date_o)*100/COUNT(regionn) AS ratio
,   SUM(CASE WHEN gender='mr' THEN 1 ELSE 0 END) AS mrs
,   SUM(CASE WHEN gender='mme' THEN 1 ELSE 0 END) AS mmes
FROM data
WHERE length(regionn)=2
GROUP BY regionn
ORDER BY regionn ASC

答案 1 :(得分:1)

试试这个:

SELECT regionn, 
COUNT(regionn) AS total,
COUNT(last_date_o) AS ouvreurs,
COUNT(last_date_o)*100/COUNT(regionn) AS ratio,
COUNT(gender='mr' or null), 
COUNT(gender='mme' or null)
FROM data WHERE length(regionn)=2
GROUP BY regionn ORDER BY regionn ASC

COUNT(gender='mr' or null)的解释:

gender == mr

count(gender='mr' or null) => count('mr'='mr' or null) => count(true or null) => count(true) => 1

gender == mme

count(gender='mr' or null) => count('mme'='mr' or null) => count(false or null) => count(null) => 0

这个技巧使用了true or null == truefalse or null == null

这一事实