我有两张桌子,车辆和阅读。
车辆表
VehicleId 名称 InitialReading
阅读表
ReadingId 日期 转移 VehicleId 阅读
现在我在结合阅读时遇到了问题。我在桌子上搜索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);
答案 0 :(得分:0)
你已经有两张桌子..现在你想要两个表格,其中车辆id = 1
只使用子查询
select R.Date R.Shift,(select V.Initial Reading From Vehicle V where v.Vehicle id =R.Vehicle Id) as Initial Reading , R.Reading as Closing Reading from Reading Where Vehicle id=@Vehicle id
or
set @Vehicle id=1
select R.Date R.Shift,(select V.Initial Reading From Vehicle V where v.Vehicle id =R.Vehicle Id) as Initial Reading , R.Reading as Closing Reading from Reading Where Vehicle id=1