我有一张这样的桌子:
date day weather
2000-01-01 Monday Sunny
2000-01-02 Tuesday Rainy
. . .
我想在一个查询中获得下雨的星期一和晴天的星期一的数量,例如
day rainy_d sunny_d
Monday 2 5
如何在 Mysql 和 PostgreSQL 中实现这一点?
我有一张这样的桌子:
date day weather
2000-01-01 Monday Sunny
2000-01-02 Tuesday Rainy
. . .
我想在一个查询中获得下雨的星期一和晴天的星期一的数量,例如
day rainy_d sunny_d
Monday 2 5
如何在 Mysql 和 PostgreSQL 中实现这一点?
标准 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
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`
该列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 提供的替代方法。