Conditional clause in COUNT
Answer a question I have a problem in my request: 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(gen
Answer a question
I have a problem in my request:
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
the gender column has 2 possible values: 'mr' or 'mme'. With COUNT(gender='mr'), COUNT(gender='mme') I want the total of each, but the same value is return.
In fact COUNT(gender='mr'), COUNT(gender='mme') is exactly the same as COUNT(gender), COUNT(gender)...
How can I do that?
Answers
COUNT
is not the right aggregator for this, you should use SUM
.
In fact
COUNT(gender='mr')
,COUNT(gender='mme')
is exactly the same asCOUNT(gender)
This is because COUNT
counts anything that's not NULL
, while SUM
will add up ones and zeros.
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
更多推荐
所有评论(0)