如何根据图片得到我的结果

时间:2018-11-21 08:09:09

标签: sql-server sql-server-2008 sql-server-2012 sql-server-2014

我在下面的查询中要显示数据fromCityIdToCityId。假设旅客旅行fromCity伦敦toCity曼彻斯特。我如何编写这样的查询,当我使用where子句和in时,它向我显示fromcitytocity中的相同值 预期结果在下面的图片中

      Select vh.VoucharId,fCity.CityName as FromCity, tCity.CityName as ToCity, InDate 
from VoucharHotel vh  
inner join City fCity on   vh.CityId = fCity.CityId  inner join City tCity on
 vh.CityId = tCity.CityId 
 where vh.InDate  between '11/15/2018 12:00:00 AM' and '11/16/2018 12:00:00 AM'   AND vh.CityId in (1,2)

enter image description here

enter image description here

  CREATE TABLE VoucharHotel (
        ID int IDENTITY(1,1) PRIMARY KEY,
        VoucharId Int ,
        CityId int,
        HotelId  int,
        InDate Datetime,
        OutDate Datetime
    );

    CREATE TABLE City (
        CityId int IDENTITY(1,1) PRIMARY KEY,
        CityName varchar(200),
    );
    insert into City Values('London')
    insert into City Values('Manchester')
    insert into City Values('Birmingham')
    insert into City Values('Leeds')

    CREATE TABLE HotelMaster (
        HotelId int IDENTITY(1,1) PRIMARY KEY,
        HotelName varchar(200),
    );
    insert into HotelMaster Values('London Hotel')
    insert into HotelMaster Values('Manchester Hotel')
    insert into HotelMaster Values('Birmingham Hotel')
    insert into HotelMaster Values('Leeds Hotel')

    Insert into VoucharHotel Values(22,1,1,'11/15/2018', '11/16/2018')
    Insert into VoucharHotel Values(22,2,2,'11/16/2018', '11/18/2018')
    Insert into VoucharHotel Values(22,1,1,'11/18/2018', '11/20/2018')

    Insert into VoucharHotel Values(23,2,2,'11/16/2018', '11/17/2018')
    Insert into VoucharHotel Values(23,4,4,'11/17/2018', '11/20/2018')
    Insert into VoucharHotel Values(23,2,2,'11/20/2018', '11/26/2018')

1 个答案:

答案 0 :(得分:0)

您的起始表应该是表VoucharHotel上的联接,例如:

Select V1.VoucharId, V1.CityId, V2.HotelId  ,V1.InDate
from  VoucharHotel  V1
join VoucharHotel V2 on V1.VoucharId  = V2.VoucharId  and convert(date,V1.OutDate) = dateadd(day,-1,convert(date,V2.InDate ) )

从这里只需将联接添加到“城市表”并在所需的日期进行过滤