计算适合多个类别的行

时间:2015-10-05 08:13:17

标签: mysql

我无法正确显示MySQL查询的结果。

我有一张桌子,旅行,列出了汽车旅行的开始和结束时间(开始和结束时间是午夜后的分钟数)。

id   start    end
1    0        120    // 00:00    02:00
2    60       90     // 01:00    01:30
3    0        150    // 00:00    02:30
etc...

我想算一下“活跃”的数量。每半个小时开车一次,所以我的结果看起来像这样:

period          count
00:00 - 00:30   2
00:30 - 01:00   2
01:00 - 01:30   3
01:30 - 02:00   2
02:00 - 02:30   1
02:30 - 03:00   0

注1:旅行表中的每一行可能会计入多个期间。

注意2:我认为开始时间是包容性的,而结束时间是非包容性的,所以例如行程2仅计入期间' 00 - 13:30'。

我无法以这种方式呈现结果。我目前的疑问是:

SELECT
    sum(start < 30 AND end > 0) as '00:00 - 00:30',
    sum(start < 60 AND end > 30) as '00:30 - 01:00',
    sum(start < 90 AND end > 60) as '01:00 - 01:30',
    etc...
FROM
    trips;

产生以下结果:

00:00 - 00:30    00:30 - 01:00    01:00 - 01:30   etc...
2                2                3

为了澄清,我的解决方案产生了正确答案,但我希望每行显示一个句点,而不是每列一个句点。 我想解决方案是将CASE与GROUP BY一起使用,但到目前为止我还没有成功。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

CREATE TABLE创建一个表格,或者动态创建一个表格。

select period.text, count(*)
from
(
  select   0 as min_start,  30 as min_end, '00:00 - 00:30' as text
  union all
  select  30 as min_start,  60 as min_end, '00:30 - 01:00' as text
  union all
  select  60 as min_start,  90 as min_end, '01:00 - 01:30' as text
  union all
  select  90 as min_start, 120 as min_end, '01:30 - 02:00' as text
  union all
  select 120 as min_start, 150 as min_end, '02:00 - 02:30' as text
  union all
  select 150 as min_start, 180 as min_end, '02:30 - 03:00' as text
) period
left join mytable on mytable.min_start < period.min_end
                  and mytable.min_end > period.min_start
group by period.text;

SQL小提琴:http://www.sqlfiddle.com/#!9/8df7d/5