我的请求中有问题:
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>
我该怎么做?
感谢您的帮助
答案 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 == true
和false or null == null