嗨,我有三个表格列
vehicle_id int(11)auto_increment primary_key,
vehicle_reg_no varchar(100)not_null,
inp_datetime datetime not_null
我需要提取这些数据。
车辆注册号 | 1月 | 2月 | March ....... 12月 | 总计
到目前为止,我做了这个查询,但我没有得到预期的值。
SELECT COUNT(vehicle_master.vehicle_id)as countVal,
vehicle_master.vehicle_reg_no,
MONTHNAME(STR_TO_DATE(EXTRACT(MONTH FROM vehicle_master.inp_datetime),'%m'))as monthName
FROM vehicle_master
GROUP BY vehicle_master.inp_datetime
答案 0 :(得分:1)
我不确定你的架构,但从我所看到的你可以只是寻找这个:
SELECT DATE_FORMAT(vm01.inp_datetime,"%M") as monthName
, COUNT(*) as countVal
FROM vehicle_master vm
GROUP BY monthName
Month | Count
------------------
January | 10
February | 13
March | 4
etc | etc
然而,我有点觉得这不是你想要做的事情,在这种情况下,这可能会给你一个想法(或者至少这会给你输出,因为你&#39 ; ve指定了上述内容):
SELECT vm.vehicle_reg_no as `Vehicle Register Number`
, COUNT(mv01.*) as January
, COUNT(mv02.*) as February
, COUNT(mv03.*) as March
-- , COUNT(mv04.*) as etc
, COUNT(mv.*) as Total
FROM vehicle_master vm
LEFT JOIN vehicle_master vm01 on vm01.vehicle_id=vm.vehicle_id and vm01.vehicle_reg_no=vm.vehicle_reg_no and vm01.inp_datetime=vm.inp_datetime and DATE_FORMAT(vm01.inp_datetime,"%m") = "01"
LEFT JOIN vehicle_master vm02 on vm02.vehicle_id=vm.vehicle_id and vm02.vehicle_reg_no=vm.vehicle_reg_no and vm02.inp_datetime=vm.inp_datetime and DATE_FORMAT(vm02.inp_datetime,"%m") = "02"
LEFT JOIN vehicle_master vm03 on vm03.vehicle_id=vm.vehicle_id and vm03.vehicle_reg_no=vm.vehicle_reg_no and vm03.inp_datetime=vm.inp_datetime and DATE_FORMAT(vm03.inp_datetime,"%m") = "03" -- etc
GROUP BY vehicle_reg_no