2012-05-22 58 views

回答

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` 
+0

完美地工作。謝謝 – user1267132

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 
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提供的替代方法。

相關問題