我有這樣一個表:行計數column1在= 'VALUE1' 和列1 = '值' 組由COLUMN2
date day weather
2000-01-01 Monday Sunny
2000-01-02 Tuesday Rainy
。 。 。
我想多雨星期一和陽光明媚的週一的數量在一個查詢像
day rainy_d sunny_d
Monday 2 5
如何做到在MySQL和PostgreSQL?
我有這樣一個表:行計數column1在= 'VALUE1' 和列1 = '值' 組由COLUMN2
date day weather
2000-01-01 Monday Sunny
2000-01-02 Tuesday Rainy
。 。 。
我想多雨星期一和陽光明媚的週一的數量在一個查詢像
day rainy_d sunny_d
Monday 2 5
如何做到在MySQL和PostgreSQL?
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`
標準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
的列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提供的替代方法。
完美地工作。謝謝 – user1267132