我在sql中有以下表格。我只在这里放入少量的表数据以便于阅读,并排除与此问题无关的列。
表格旅行:
ID_Company (FK, int not null)
trip_no (PK, int not null)
表Passengers_in_trip:
trip_no (PK, FK, int not null)
id_psg (PK, FK, int not null)
date (PK, Datetime, not null)
表格中的信息如下(为便于参考,包括最少的信息);
表 - 旅行:
Trip No ID_Company
1100 4
1181 1
表 - Passengers_in_trip:
Trip No IS_Psg Date
1100 1 2015-04-02
1181 1 2015-04-15
1187 8 2015-05-19
1188 8 2015-04-27
问题/查询: 对于每家公司,查找2015年4月运输的乘客数量(如果有的话),为期十天。
我尝试了以下语法/代码
SELECT Trip.ID_Comp, COUNT(Pass_in_trip.ID_Psg) AS Total_PassengerNos,
Pass_in_trip.date
FROM Trip
JOIN Pass_in_trip
ON Trip.trip_no = Pass_in_trip.trip_no
WHERE Pass_in_trip.date BETWEEN '2015-04-01' AND '2015-04-30'
AND DATEDIFF(day, '2015-04-01', '2015-04-30') % 10 = 0
GROUP BY Pass_in_trip.date, Trip.ID_comp
ORDER BY Pass_in_trip.date ASC;
我得到的结果是,只有标题,没有数据
ID_Company Total_PassengerNos Date
我决定退一步,并尝试从表Passengers_in_trip中选择所有内容,只是为了尝试找到我的错误,所以我完成了以下语法
SELECT * FROM Pass_in_trip
WHERE date BETWEEN '2015-04-01' AND '2015-04-30'
AND DATEDIFF(day, '2015-04-01', '2015-04-30') % 10 = 0
这给了我下面的表格,其中包含空白结果或没有数据
trip_no ID_psg Date
如果有人可以帮助我并指导我出错的地方,我会非常感激,因为我已经搜索过这个问题的答案,现在我仍然坚持这个。
谢谢大家 乔西
答案 0 :(得分:1)
我想你想要前10天乘客数量,接下来10天......你需要改变分组:
SELECT Trip.ID_Comp,
datediff(day, '20150401', Pass_in_trip.date) / 10 as monthPart,
COUNT(Pass_in_trip.ID_Psg) AS Total_PassengerNos,
FROM Trip
JOIN Pass_in_trip ON Trip.trip_no = Pass_in_trip.trip_no
WHERE Pass_in_trip.date >= '2015-04-01' AND Pass_in_trip.date < '2015-05-01'
GROUP BY datediff(day, '20150401', Pass_in_trip.date) / 10, Trip.ID_comp