我在下面的查询中要显示数据fromCityId
和ToCityId
。假设旅客旅行fromCity
伦敦toCity
曼彻斯特。我如何编写这样的查询,当我使用where
子句和in
时,它向我显示fromcity
和tocity
期望的结果在下面的图片中
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)
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')
答案 0 :(得分:0)
以下方法可以解决您的问题:
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)
让我知道您是否需要进行更改。