【问题标题】:sql server join return only one row from second tablesql server join 从第二个表只返回一行
【发布时间】:2014-10-01 05:22:49
【问题描述】:

我有两张桌子,Vehicle 和 Reading。

车辆表

VehicleId 名称 InitialReading

  1. ABC 584
  2. XYZ 900

阅读表

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

现在我在合并读数时遇到问题。我正在表格中搜索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

【问题讨论】:

  • 你的问题可能来自交叉申请吗? @ 987654322@ 当我读到在我看来,交叉应用也(?可选?)组成一个组,可以解释为什么只有一个结果(这样做是作为评论而不是答案,因为我不确定那里)
  • 正如我在问题中所说,当我们考虑一个日期时,我需要在该日期之前最后输入的读数作为开始读数。因此,如果我获取多于一行,结果将是错误的。

标签: c# sql asp.net sql-server-2008 sql-server-2008-r2


【解决方案1】:

你已经有两个表了。现在你想合并两个表,其中 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

【讨论】:

  • 我没有合并两个表,我是从同一个表中获取开始和结束的读数。请检查所需的输出。我正在进入一天并在同一张桌子上进行明智的阅读。如果没有开始读数,即表中的第一个条目,我必须从车辆表中获取初始读数。
猜你喜欢
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 2010-12-21
  • 2012-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多