如何使用另一个将列拆分为多个值

时间:2012-03-06 07:34:40

标签: mysql split

我有下表: 日期,小时,事故

我必须在白天和晚上得到事故的数量。

以下是如何在一天内获得它

  

选择日期,SUM(意外)AS'当日'车辆在哪里日期> ='2012-01-01'和日期< ='2012-01-31'和小时> = '00:00:00' AND HOUR< ='11:59:59'GRUUP BY date

如何修改查询以便在晚上发生事故?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

在晚上和白天意味着整天,所以只需删除你的条件

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

答案 2 :(得分: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)构造计算“夜晚”或“日期”(请注意,根据您的小时列类型,您可能需要使用HOUR >= '00:00:00' AND HOUR <= '11:59:59'代替BETWEEN)。

然后按日期和日/夜分组,以获得每日和每期的总和。

答案 3 :(得分: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