簡體   English   中英

sql server join僅從第二個表返回一行

[英]sql server join return only one row from second table

我有兩個表,Vehicle和Reading。

車輛桌

VehicleId 名稱 InitialReading

  1. ABC 584
  2. XYZ 900

閱讀桌

ReadingId 日期 轉換 VehicleId 閱讀

  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

現在我在合並讀數時遇到問題。 我正在表格中搜索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說的實驗

您已經有兩個表了。現在您想要合並兩個表,其中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=@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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM