2012-03-06 68 views
0

我有如下表: 日期,小時,事故如何使用拆分列到多個值另一個

我得事故數量在白天和黑夜。

這裏是如何得到它一天

選擇日期,SUM(事故)AS '在天' 從車上其中date> ='2012-01-01 'AND DATE < =' 2012- 01-31' 和小時> = 00:00:00「和小時< =「11:59:59」 GRUUP BY日期

如何修改查詢,也有在晚上的事故?

回答

0

我在這裏打招呼,但;

SELECT date,SUM(CASE WHEN HOUR>='00: 00:00' AND HOUR<=' 11:59:59 
THEN accidents ELSE 0 END) 
AS 'at day', 
SUM(CASE WHEN HOUR>='12: 00:00' AND HOUR<=' 23:59:59 
THEN accidents ELSE 0 END) AS 'at night' 
FROM vehicles 
WHERE DATE>='2012-01-01 'AND DATE<='2012-01-31' 
GROUP BY date 
+0

謝謝,作品gr8! – breq 2012-03-06 09:21:47

0

你可以使用一個union

SELECT date, SUM(accidents) AS 'at day', '' as 'at night' 
FROM vehicles 
WHERE DATE>='2012-01-01 ' AND DATE<='2012-01-31' 
AND HOUR>='00: 00:00' AND HOUR<=' 11:59:59 ' 
GROUP BY date 
union 
SELECT date, '', as 'at day', SUM(accidents) AS 'at night' 
FROM vehicles 
WHERE DATE>='2012-01-01 ' AND DATE<='2012-01-31' 
AND HOUR>='12: 00:00' AND HOUR<=' 23:59:59 ' 
GROUP BY date 

或使用case

SELECT date, '', as 'at day', 
     SUM(accidents) AS 'sum_accidents', 
     case `HOUR` between '00: 00:00' and '11:59:59' THEN 'night' ELSE 'day' END as 'night_or_day' 
FROM vehicles 
WHERE DATE>='2012-01-01 ' AND DATE<='2012-01-31' 
GROUP BY date 
+0

嘿,謝謝,它的工作原理! (第一個解決方案),但我怎麼能在第一行中得到這個空的空間? http://screenshooter.net/0562655/06_03_2012__09_14_41並得到它像這樣http://screenshooter.net/0562655/06_03_2012__09_17_38?我嘗試了UNION ALL,但它不起作用 – breq 2012-03-06 08:14:58

+0

如果您使用第二種解決方案,您將在一列中加上一個額外的列,指示它是在白天還是在晚上 – 2012-03-06 08:23:33

0

在夜間和在天的意思是整天,所以才刪除小時條件

SELECT date, SUM(accidents) AS 'at day' FROM vehicles WHERE DATE>='2012-01-01 'AND DATE<='2012-01-31' GRUUP BY date 
0

你可以省略HOUR上的WHERE條件和GROUP BY

SELECT date, 
     IF(HOUR BETWEEN '00:00:00' AND '11:59:59','day','night') as period, 
     SUM(accidents) as numAccidents 
FROM vehicles 
WHERE Date >= '2012-01-01' AND DATE <= '2012-01-31' 
GROUP BY Date, IF(HOUR BETWEEN '00:00:00' AND '11:59:59','day','night') 

此計算「夜」或使用IF(condition,then,else)結構「天」(注意:根據您的時間列的類型,你可能必須使用​​而不是BETWEEN)。

然後,它會根據日期和日/夜進行分組,以獲得每天和週期的總和。