我有下面的图片和查询。问题是我的查询显示我的值不正确,在多个记录中没有显示正确的hotelname,这意味着我想要VoucherHotelTable中的第一家酒店,但是由于与众不同,它向我显示了第二家酒店,我想请您帮我这个如何处理
Select distinct v.VoucherId,u.Name,v.ArrivalFromCity,
CAST(v.ArrivalDate AS DATE) as ADDate, v.ArrivalFlightNo, hm.HotelName
from VoucherMaster v
inner join UserMaster u on v.AgentId = u.UserId
inner join VoucharHotel vh on v.VoucherId = vh.VoucharId
inner join HotelMaster hm on vh.HotelId = hm.HotelId
inner join AirportTerminal t on v.ArrivalTerminalId = t.AirprtTerminalId
where v.ArrivalDate between '11/15/2018 12:00:00 AM'
and '11/16/2018 12:00:00 AM' AND v.ArrivalSectorId = 3
答案 0 :(得分:1)
此查询正在按分区工作。 尝试这个。 rank()函数应返回每个凭证的酒店等级。
;with VoucherHotelRnk as (
select voucherId, hotelId, date, rank() over(partition by voucherId order by date) rnk
from VoucharHotel
)
Select v.VoucherId,u.Name,v.ArrivalFromCity,
CAST(v.ArrivalDate AS DATE) as ADDate, v.ArrivalFlightNo, hm.HotelName
from VoucherMaster v
inner join UserMaster u on v.AgentId = u.UserId
inner join VoucherHotelRnk vh on v.VoucherId = vh.VoucherId and vh.rnk = 1
inner join HotelMaster hm on vh.HotelId = hm.HotelId
inner join AirportTerminal t on v.ArrivalTerminalId = t.AirprtTerminalId
where v.ArrivalDate between '11/15/2018 12:00:00 AM'
and '11/16/2018 12:00:00 AM' AND v.ArrivalSectorId = 3
答案 1 :(得分:-1)
;with VoucherHotelRnk as (
select voucherId, hotelId, date, ROW_NUMBER() over(partition by voucherId order by date) rowcount
from VoucharHotel
)
Select v.VoucherId,u.Name,v.ArrivalFromCity,
CAST(v.ArrivalDate AS DATE) as ADDate, v.ArrivalFlightNo, hm.HotelName
from VoucherMaster v
inner join UserMaster u on v.AgentId = u.UserId
inner join VoucherHotelRnk vh on v.VoucherId = vh.VoucherId and vh.rowcount= 1
inner join HotelMaster hm on vh.HotelId = hm.HotelId
inner join AirportTerminal t on v.ArrivalTerminalId = t.AirprtTerminalId
where v.ArrivalDate between '11/15/2018 12:00:00 AM'
and '11/16/2018 12:00:00 AM' AND v.ArrivalSectorId = 3