简体   繁体   中英

sql server join return only one row from second table

I have two tables, Vehicle and Reading.

VEHICLE TABLE

VehicleId Name InitialReading

  1. ABC 584
  2. XYZ 900

READING TABLE

ReadingId Date Shift VehicleId Reading

  1. 2014-09-01 1 1 1234
  2. 2014-09-01 2 1 2230
  3. 2014-09-02 1 1 2500
  4. 2014-09-02 2 1 3004
  5. 2014-09-03 2 1 5000
  6. 2014-09-03 1 1 4000
  7. 2014-09-01 1 2 1000

Now I am having problem in combining the readings. I am searching the table for a VehicleId

for example, VehicleId=1 , then the output has to be in the following format.

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

I have tried this with 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

Already You Have Two table.. Now You Want combining two table where Vehicle id=1

just Use Sub Query

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM