2014-10-01 71 views
0

我有两张表,Vehicle和Reading。sql server join从第二张表中只返回一行

车辆TABLE

VehicleId名称InitialReading

  1. ABC 584
  2. XYZ 900

读取台

ReadingId日期移位VehicleId

  1. 2014年9月1日1 1 1234
  2. 2014年9月1日2 1 2230
  3. 2014-09-02 1 1 2500
  4. 2014年9月2日2 1 3004
  5. 2014年9月3日2 1 5000
  6. 2014年9月3日1 1 4000
  7. 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

+0

它可能是你的问题来自于交叉应用吗? http://sqlserverplanet.com/sql-2005/cross-apply-explained当我读到它在我看来,交叉应用(?可选?)使得一个组可以解释为什么只有1结果(做这是作为评论而不是答案,因为我不确定那里) – Thomas 2014-10-01 06:19:48

+0

正如我在问题中所说的,当我们考虑一个日期时,我需要在该日期之前的最后输入的阅读作为开始阅读。所以如果我获取多于一行的结果将是错误的。 – Sajeel 2014-10-01 08:22:20

回答

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 [email protected] 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 
+0

我没有合并两个表格,我从同一张表格中读取开始和结束读数。请检查所需的输出。我正在进入一天,并在同一张桌子上进行明智的阅读。如果没有开始读数,即对于表格中的第一个条目,我必须从车辆表中读取初始读数。 – Sajeel 2014-10-03 06:26:36

相关问题