行计数,其中column1 ='value1',column1 ='value2'group by column2

时间:2012-05-22 17:43:44

标签: mysql postgresql count group-by

我有一张这样的表:

date         day     weather
2000-01-01   Monday  Sunny
2000-01-02   Tuesday Rainy

。 。

我希望在一个查询中获得多雨的星期一和阳光明媚的星期一,如

day     rainy_d  sunny_d
Monday  2        5

如何在Mysql和PostgreSQL中实现它?

3 个答案:

答案 0 :(得分:1)

select `Day`, 
SUM(case when weather = 'Sunny' THEN 1 ELSE 0 end) as Sunny_D,
SUM(case when weather = 'Rainy' THEN 1 ELSE 0 end) as Rainy_D
FROM YOURTABLENAME
Where day = 'Monday'
Group by `Day`

答案 1 :(得分:1)

标准SQL,适用于:

SELECT
    day,
    SUM(CASE WHEN weather = 'Rainy' THEN 1 ELSE 0 END) AS rainy_d,
    SUM(CASE WHEN weather = 'Sunny' THEN 1 ELSE 0 END) AS sunny_d
FROM yourtable
GROUP BY day

更简洁的版本 - 仅限MySQL:

SELECT
    day,
    SUM(weather = 'Rainy') AS rainy_d,
    SUM(weather = 'Sunny') AS sunny_d
FROM yourtable
GROUP BY day

更简洁的版本 - 仅限PostgreSQL:

SELECT
    day,
    SUM((weather = 'Rainy')::int) AS rainy_d,
    SUM((weather = 'Sunny')::int) AS sunny_d
FROM yourtable
GROUP BY day

答案 2 :(得分:0)

day可能是多余的。我会删除它而不用替换。列date包含所有信息。然后你的查询看起来像这样......

在PostgreSQL中:

SELECT to_char(date, 'Day') AS day
      ,COUNT(NULLIF(weather,'Sunny')) AS rainy_d
      ,COUNT(NULLIF(weather,'Rainy')) AS sunny_d
FROM   tbl
GROUP  BY 1;

在MySQL中:

SELECT DAYNAME(date) AS day
... rest identical

NULLIF()构造适用于weather列中的两个不同(非空)值,并且是标准SQL。有关更多值,请使用@Mark和@xQbert提供的替代方法。