*********情景**************
我有公共汽车运营,一些公共汽车在一天内不止一次加油,让我们说一辆公共汽车(4345)在2017年9月4日充满燃料,并在2017年9月3日填充燃料2次
我有查询从某个日期开始运行(DateFrom和DateTo)并获取每个车辆的燃料条目,这些条目在所选日期范围内不止一个.........但我需要什么 从某些日期范围(DateFrom - DateTo)和每个车辆的每个日期下的结果,车辆填充燃料的次数...为了更好地理解,您可以看到附加的图像.... 我正在使用的查询是:
WITH Records_counts AS
(
SELECT f.*, COUNT(*) OVER (PARTITION BY bus1) ct
FROM Fuel.vFuelEntriesDetails f
)
SELECT * FROM Records_counts WHERE ct > 1
AND FuelEntryDate >='2017-09-03' and FuelEntryDate <'2017-09-05'
AND ( BusNo BETWEEN '10161/1' AND '10180/1' )
ORDER BY BusNo DESC
答案 0 :(得分:1)
正如@Gordon Linoff所说,请提供样本数据,以便清楚地了解预期的输出。
我已经根据我的理解为示例演示创建了以下表格:
表:
create table tbl_vehicle
(
busno varchar(10),
plateno int,
coldate date
);
记录:
insert into tbl_vehicle values('1016/1',4345,'2017-09-03'),('1016/1',4345,'2017-09-03'),
('1016/1',4345,'2017-09-03'),('1016/1',4345,'2017-09-04');
查询:
SELECT plateno,coldate,COUNT(*) as fuel_fill_count
FROM tbl_vehicle
WHERE coldate BETWEEN '2017-09-03' and '2017-09-05'
and busno BETWEEN '1016/1' AND '10180/1'
GROUP BY plateno,coldate
输出:
plateno coldate fuel_fill_count
------------------------------------
4345 2017-09-03 3
4345 2017-09-04 1
注意:在SQL Server 2008 R2上测试。
答案 1 :(得分:0)
你可以试试这个。
;WITH Records_counts AS
(
SELECT f.*, COUNT(*) OVER (PARTITION BY FuelEntryDate, BusNo) ct
FROM Fuel.vFuelEntriesDetails f
)
SELECT * FROM Records_counts WHERE
FuelEntryDate >='2017-09-03' and FuelEntryDate <'2017-09-05'
AND ( BusNo BETWEEN '10161/1' AND '10180/1' )
ORDER BY BusNo DESC
答案 2 :(得分:0)
答案 3 :(得分:0)
答案 4 :(得分:0)
您不需要cte,只需将日期添加到分区中 由于您的FuelEntryDate是日期时间,因此您只需要使用日期部分
SELECT DATE(FuelEntryDate) EntryDate, f.*, COUNT(*) OVER (PARTITION BY Busno, Date(FuelEntryDate)) ct
FROM Fuel.vFuelEntriesDetails f
WHERE
FuelEntryDate BETWEEN '2017-09-03' AND FuelEntryDate '2017-09-05'
AND ( BusNo BETWEEN '10161/1' AND '10180/1' )
ORDER BY BusNo, FuelEntryDate