SQL以不同方式连接相同的列

时间:2016-03-22 18:31:28

标签: sql-server join

select top 1000 
    f.*, s.TimeZoneCode as TimeZoneOrigin, 
    s2.TimeZoneCode as TimeZoneDestination,
    tz.StandardVariation as VariationOrigin, 
    tz2.StandardVariation as VariationDestination, 
    tzv.Variation as TimeVariation, 
    tzv2.Variation as TimeVariation2
from 
    REZNVWB01.MIT.HVResearchDataSetDraft1 f
inner join 
    REZNVOD01.dbo.Station s on s.StationCode = f.TripOriginLocationCode 
inner join 
    REZNVOD01.dbo.Station s2 on s2.StationCode = f.TripDestinationLocationCode 
inner join 
    REZNVOD01.dbo.TimeZone tz on tz.TimeZoneCode = s.TimeZoneCode
inner join 
    REZNVOD01.dbo.TimeZone tz2 on tz2.TimeZoneCode = s.TimeZoneCode
inner join 
    REZNVOD01.dbo.TimeZoneVariation tzv on tzv.TimeZoneCode = s.TimeZoneCode 
                                        and tzv.EndUTC >= BookingDate
                                        and tzv.StartUTC <= BookingDate

每行有一个StartUTCEndUTCtimezonevariation的表格。我想查看BookingTime,并在timezonevariationbookingtime之间获得StartUTC

我需要在此代码中更改哪些内容?

EndUTC

如果TimeZoneVariation代码StartUTC和EndUTC在条件之间(IE startUTC可能是5:00,endUTC可能是10:00,我想要TimeZoneVariation值,其中BookingDate在startUTC和endUTC之间),这段代码是否正确

1 个答案:

答案 0 :(得分:1)

要回答您的第一个问题 - 仅仅通过逻辑 - 您可以使用BETWEEN语句,这可以使您的意图更清晰。 BETWEEN是包容性的,这意味着它包括比较范围两端的值:

 INNER JOIN REZNVOD01.dbo.TimeZoneVariation tzv
   ON tzv.TimeZoneCode = s.TimeZoneCode AND
      BookingDate BETWEEN tzv.EndUTC AND tzv.StartUTC

但是,您没有说明“BookingDate”是“f”中的字段还是变量。如果它是一个变量,请确保在商业广告(@)前面添加,如果它来自“f”,请将其声明为(E.G. f.BookingDate)。这种做法将使您的代码更清楚地阅读它。

关于你的最终查询...拼写你的表别名而不是简单地缩写它们可能是有益的(我喜欢打破我的行并做缩进以帮助可视化连接关系):

SELECT TOP 1000
  f.*,
  origStation.TimeZoneCode AS TimeZoneOrigin,
  destStation.TimeZoneCode AS TimeZoneDestination,
  origTz.StandardVariation AS VariationOrigin,
  destTz.StandardVariation AS VariationDestination,
  origTzv.Variation AS TimeVariationOrigin,
  destTzv.Variation AS TimeVariationDestination
FROM
  REZNVWB01.MIT.HVResearchDataSetDraft1 AS f
    INNER JOIN REZNVOD01.dbo.Station AS origStation
      ON origStation.StationCode=f.TripOriginLocationCode 
    INNER JOIN REZNVOD01.dbo.Station AS destStation
      ON destStation.StationCode=f.TripDestinationLocationCode 
    INNER JOIN REZNVOD01.dbo.TimeZone AS origTz
      ON origTz.TimeZoneCode=origStation.TimeZoneCode
    INNER JOIN REZNVOD01.dbo.TimeZone AS destTz
      ON destTz.TimeZoneCode=destStation.TimeZoneCode
    INNER JOIN REZNVOD01.dbo.TimeZoneVariation AS origTzv
      ON origTzv.TimeZoneCode = origStation.TimeZoneCode AND
         f.BookingDate BETWEEN origTzv.EndUTC AND origTzv.StartUTC
    INNER JOIN REZNVOD01.dbo.TimeZoneVariation AS destTzv
      ON destTzv.TimeZoneCode = destStation.TimeZoneCode AND
         f.BookingDate BETWEEN destTzv.EndUTC AND destTzv.StartUTC

我不太明白你的上一个问题。请你重申一下吗?

谢谢!