如何在mysql查询中获取两个日期范围内的时间间隔记录

时间:2017-01-16 13:29:56

标签: mysql

我试图在2017-01-17和2017-01-18之间的两个日期范围内获取记录并显示每小时范围内可用车辆类型的数量,我的查询结果不是很好它超越了范围。

我的查询如下:

select c.vtype, 
   ( select COUNT(vtype) from Availability where DATE_FORMAT(DateIn, '%H:%i') > '08:00' AND DATE_FORMAT(DateOut, '%H:%i') < '10:00' AND vtype =c.vtype ) as Eight,
   ( select COUNT(vtype) from Availability where DATE_FORMAT(DateIn, '%H:%i') > '10:00' AND DATE_FORMAT(DateOut, '%H:%i') < '12:00' AND vtype =c.vtype ) as Ten,
   ( select COUNT(vtype) from Availability where DATE_FORMAT(DateIn, '%H:%i') > '12:00' AND DATE_FORMAT(DateOut, '%H:%i') < '14:00' AND vtype =c.vtype ) as Twelve,
   ( select COUNT(vtype) from Availability where DATE_FORMAT(DateIn, '%H:%i') > '14:00' AND DATE_FORMAT(DateOut, '%H:%i') < '16:00' AND vtype =c.vtype ) as Tow,
   ( select COUNT(vtype) from Availability where DATE_FORMAT(DateIn, '%H:%i') > '16:00' AND DATE_FORMAT(DateOut, '%H:%i') < '00:00' AND vtype =c.vtype ) as Four

   from Availability AS c where c.costCente = '254' AND ('2017-01-17 00:00' BETWEEN c.DateIn AND c.DateOut) AND ('2017-01-18 23:59' BETWEEN c.DateIn AND c.DateOut)

   GROUP BY c.vtype ORDER BY c.vtype DESC

我的表看起来像这样:

vtype           vmodel     costCente    department    DateIn                 DateOut
----------------------------------------------------------------------------------------
MOTO BIKE       YBR125     254           403         2017-01-16 16:38   2017-01-25 08:54
MOTO BIKE       STARLX     254           408         2017-01-17 13:30   
PICK UP         D/CB       254           418         2017-01-17 10:58   
MOTO BIKE       MAX100R    254           418         2017-01-18 09:59   2017-01-19 07:59
MOTO BIKE       BOXER-BM   256           407         2017-01-26 08:09   2017-01-31 07:23
MOTO BIKE       MAX100R    254           403         2017-01-15 12:37   2017-01-15 04:37
TYT             HILUX      254           410         2017-01-17 08:39   2017-01-20 09:39
MOTO BIKE       MAX100R    254           403         2017-01-16 08:41   2017-01-31 09:41
SALOON          PATROL     254           403         2017-01-18 07:45   2017-01-30 07:45
PICK UP         D/CB       254           418         2017-01-17 13:58   
PICK UP         D/CB       254           418         2017-01-17 15:58

我希望看到的结果是这样的,以显示可用性:

vtype       Eight    Ten        Twelve    Tow      Four
-------------------------------------------------------
MOTO BIKE     5       2           2        1        1
PICK UP       2       0           1        4        0
MOTO BIKE     0       2           2        0        0
MOTO BIKE     3       1           4        1        2   

0 个答案:

没有答案