如何从SQL Server中的左连接中选择最新记录?

时间:2017-11-16 02:36:30

标签: sql sql-server

我有一个表视图定义为:

CREATE view [SIR_SUMMARY]
AS
    SELECT
        dimsite.[SiteCode],
        dimsite.[SiteName],
        dimsite.[CityOrLocal] as City,
        dimsite.[State],
        dimsite.PostCode as Zip,
        analysis.[ProductName] as GardeName,
        analysis.[AnalysisTypeName] as ReportingType,
        analysis.LastObsDate as ReportingDate
    FROM
        LOBDW.bjs.udv_BJS_DIM_SITE dimsite
    LEFT JOIN 
       [LOBDW].[bjs].[udv_BJS_FACT_SIRA_ANALYSES] analysis ON dimsite.LegSiteId = analysis.LegSiteId  

上述视图会针对不同的 ReportingDate 返回三条记录;我想为最新的 ReportingDate 返回单行。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用窗口功能:

create view [SIR_SUMMARY] as
    select . . .
    from LOBDW.bjs.udv_BJS_DIM_SITE bds left join
         (select a.*,
                 row_number() over (partition by LegSiteId order by ReportingDate desc) as seqnum
          from [LOBDW].[bjs].[udv_BJS_FACT_SIRA_ANALYSES] a
         ) a
         on bds.LegSiteId = a.LegSiteId and a.seqnum = 1;

请注意,我更改了表别名。我认为较短的查询更容易使用。