Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

how to get data from SQL server ToCityId And FromCityId Bases

I have below query I want to show data fromCityId AND ToCityId . Suppose passenger travel fromCity London toCity Manchester. How do I write query like this, when I use where clause and in, its show me same values in fromcity and tocity

Expected results are in below Picture

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

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')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Would the below resolve your problem:

with cte
(VoucherID,FromCity,ToCity,InDate)
as
(
select
    vh.VoucharId
,   fCity.CityName as FromCity
,   tCity.CityName as ToCity
,   InDate
from        VoucharHotel    vh
inner join  City            fCity on    vh.City = fCity.CityId
inner join  City            tCity on    vh.City = tCity.CityId 
where       vh.InDate  between '11/15/2018 12:00:00 AM' and '11/16/2018 12:00:00 AM'
)

select
*
from    cte
where   City in (1,2)

Let me know if you need changes made.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...