【问题标题】:Subquery for MAX() value from LeftJoin来自 LeftJoin 的 MAX() 值的子查询
【发布时间】:2020-11-05 15:12:53
【问题描述】:

我在 SQL Server 中有这个查询,我想知道它是否可以更短?

我已经对所有列进行了子查询(带有分组依据),只是为了获取来自表左连接的 3 个日期的 MAX() 值。

我想我不能没有子查询来获取 3 个日期的 MAX()。

SELECT otherCol1
    ,otherCol2 
    ,MAX(UnsubscribedDate) AS UnsubscribedDate
    ,MAX(OpenedDate) AS OpenedDate
    ,MAX(ClickedDate) AS ClickedDate
FROM (
    SELECT otherCol1
        ,otherCol2
        ,tu.JoinDate AS UnsubscribedDate
        ,trkOp.Clicktime AS OpenedDate
        ,trkRes.Clicktime AS ClickedDate
    FROM v_members_email_occurrence vmec
    LEFT JOIN tracking_unsubscribed tu WITH (NOLOCK) ON tu.ReportId = vmec.SendingId
    LEFT JOIN tracking_opened trkOp WITH (NOLOCK) ON trkOp.ReportId = vmec.SendingId
    LEFT JOIN tracking_result trkRes WITH (NOLOCK) ON trkRes.ReportId = vmec.SendingId
    WHERE vmec.MemberId = @MemberId
    ) AS Result
GROUP BY otherCol1
        ,otherCol2

【问题讨论】:

    标签: sql sql-server sql-server-2012


    【解决方案1】:

    您可以在没有子查询的情况下进行聚合:

    SELECT otherCol1
        ,otherCol2
        ,MAX(tu.JoinDate) AS UnsubscribedDate
        ,MAX(trkOp.Clicktime) AS OpenedDate
        ,MAX(trkRes.Clicktime) AS ClickedDate
    FROM v_members_email_occurrence vmec
    LEFT JOIN tracking_unsubscribed tu WITH (NOLOCK) ON tu.ReportId = vmec.SendingId
    LEFT JOIN tracking_opened trkOp WITH (NOLOCK) ON trkOp.ReportId = vmec.SendingId
    LEFT JOIN tracking_result trkRes WITH (NOLOCK) ON trkRes.ReportId = vmec.SendingId
    WHERE vmec.MemberId = @MemberId
    GROUP BY otherCol1
            ,otherCol2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 2019-06-02
      • 2021-12-17
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多