我有两张表,Vehicle和Reading。sql server join从第二张表中只返回一行
车辆TABLE
VehicleId名称InitialReading
- ABC 584
- XYZ 900
读取台
ReadingId日期移位VehicleId读
- 2014年9月1日1 1 1234
- 2014年9月1日2 1 2230
- 2014-09-02 1 1 2500
- 2014年9月2日2 1 3004
- 2014年9月3日2 1 5000
- 2014年9月3日1 1 4000
- 2014年9月1日1 2 1000
现在我在结合阅读时遇到问题。我正在搜索表VehicleId
例如,VehicleId=1
,那么输出必须采用以下格式。
Date Shift OpeningReading ClosingReading
2014-09-01 1 584 1234 (if there are no opening for this date, I have to fetch the initial reading)
2014-09-01 2 1234 2230
2014-09-01 1 2230 2500
2014-09-01 2 2500 3004
2014-09-01 1 3004 4000
2014-09-01 2 4000 5000
我曾试图与CROSS APPLY
create table vehicle(vehicleId int identity(1,1),name varchar(25),initialReading int);
insert into vehicle values('ABC',584),('XYZ',900);
create table reading (readingId int identity(1,1),[date] date,vehicleId int,shiftId int,reading int);
insert into reading values ('2014-09-01',1,1,1234),('2014-09-01',1,2,2230), ('2014-09-02',1,1,2500),('2014-09-02',1,2,3004),('2014-09-03',1,2,5000),('2014-09-03',1,1,4000);
SQLFiddle of the said experiment
它可能是你的问题来自于交叉应用吗? http://sqlserverplanet.com/sql-2005/cross-apply-explained当我读到它在我看来,交叉应用(?可选?)使得一个组可以解释为什么只有1结果(做这是作为评论而不是答案,因为我不确定那里) – Thomas 2014-10-01 06:19:48
正如我在问题中所说的,当我们考虑一个日期时,我需要在该日期之前的最后输入的阅读作为开始阅读。所以如果我获取多于一行的结果将是错误的。 – Sajeel 2014-10-01 08:22:20