C# sql server联接只返回第二个表中的一行

C# sql server联接只返回第二个表中的一行,c#,sql,asp.net,sql-server-2008,sql-server-2008-r2,C#,Sql,Asp.net,Sql Server 2008,Sql Server 2008 R2,我有两张桌子,汽车和阅读 车辆表 车辆ID名称首字母读入 ABC 584 XYZ 900 阅读表 读取ID日期班次车辆ID读取 2014-09-01 111234 2014-09-01 2112230 2014-09-02 112500 2014-09-02 2113004 2014-09-03 21 5000 2014-09-03 11 4000 2014-09-01 12 1000 现在我在合并阅读资料时遇到了问题。我正在表格中搜索车辆ID 例如,VehicleId=1,则输出必须采用以下格

我有两张桌子,汽车和阅读

车辆表

车辆ID名称首字母读入

  • ABC 584
  • XYZ 900
  • 阅读表

    读取ID日期班次车辆ID读取

  • 2014-09-01 111234
  • 2014-09-01 2112230
  • 2014-09-02 112500
  • 2014-09-02 2113004
  • 2014-09-03 21 5000
  • 2014-09-03 11 4000
  • 2014-09-01 12 1000
  • 现在我在合并阅读资料时遇到了问题。我正在表格中搜索
    车辆ID

    例如,
    VehicleId=1
    ,则输出必须采用以下格式

    日期转换打开读取关闭读取

    我试过交叉应用

    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);
    

    您已经有两张桌子了。。现在需要合并两个表,其中车辆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
    

    你的问题是不是来自交叉申请?当我读到,在我看来,交叉应用(也可以选择)会让一组人解释为什么只有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