现在我有一张card表,记录公交车刷卡时间、地点、线路、车牌号
如下:
id line car_id tdate station
1 301 12345 2015-01-01 6:51:22 站点1
2 301 33345 2015-01-01 7:51:22 站点1
3 301 45345 2015-01-01 12:51:22 站点3
4 301 99645 2015-01-01 15:51:22 站点2
5 301 12380 2015-01-01 17:51:22 站点1
6 301 12111 2015-01-01 18:51:22 站点2
7 301 12111 2015-01-01 21:51:22 站点4
现在我想统计各个站点的客流情况,每一条刷卡记录就算作1个客流,分时段(高峰期:7:00-9:00和17:00-19:00,其他时段为平峰期),查询301线路得到的结果应该如下:
序号 站点 高峰期客流 平峰期客流 日期
1 站点1 2 1 2015-01-01
2 站点2 1 1 2015-01-01
3 站点3 0 1 2015-01-01
4 站点4 0 1 2015-01-01
请问各位大神应该怎样写这个sql语句?
备注:不同线路的站点也有所不同,所以不能把站点写死在sql里。
------解决思路----------------------
with table1
as
(
select 1 id, '301' line, '12345' car_id, to_date('2015-01-01 06:51:22', 'yyyy-mm-dd hh24:mi:ss') tdate, '站点1' station from dual union all
select 2 id, '301' line, '33345' car_id, to_date('2015-01-01 07:51:22', 'yyyy-mm-dd hh24:mi:ss') tdate, '站点1' station from dual union all
select 3 id, '301' line, '45345' car_id, to_date('2015-01-01 12:51:22', 'yyyy-mm-dd hh24:mi:ss') tdate, '站点3' station from dual union all
select 4 id, '301' line, '99645' car_id, to_date('2015-01-01 15:51:22', 'yyyy-mm-dd hh24:mi:ss') tdate, '站点2' station from dual union all
select 5 id, '301' line, '12380' car_id, to_date('2015-01-01 17:51:22', 'yyyy-mm-dd hh24:mi:ss') tdate, '站点1' station from dual union all
select 6 id, '301' line, '12111' car_id, to_date('2015-01-01 18:51:22', 'yyyy-mm-dd hh24:mi:ss') tdate, '站点2' station from dual union all
select 7 id, '301' line, '12111' car_id, to_date('2015-01-01 21:51:22', 'yyyy-mm-dd hh24:mi:ss') tdate, '站点4' station from dual
)
select line, to_char(tdate, 'yyyy-mm-dd') as tdate1, station
, sum(case when (to_char(tdate, 'hh24:mi')>='07:00' and to_char(tdate, 'hh24:mi')<='09:00') or (to_char(tdate, 'hh24:mi')>='17:00' and to_char(tdate, 'hh24:mi')<='19:00') then 1 else 0 end)
, sum(case when (to_char(tdate, 'hh24:mi')>='07:00' and to_char(tdate, 'hh24:mi')<='09:00') or (to_char(tdate, 'hh24:mi')>='17:00' and to_char(tdate, 'hh24:mi')<='19:00') then 0 else 1 end)
from table1
group by line, to_char(tdate, 'yyyy-mm-dd'), station