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 as COUNT(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
Logo

PostgreSQL社区为您提供最前沿的新闻资讯和知识内容

更多推荐