如何解决从LeftJoin的MAX值的子查询
我在sql Server中有此查询,我想知道它是否可以更短?
我对所有列进行了一个子查询(带有group by),只是为了获得3个日期的MAX()值,这些值来自左连接表。
SELECT otherCol1,otherCol2,MAX(UnsubscribedDate) AS UnsubscribedDate,MAX(OpenedDate) AS OpenedDate,MAX(ClickedDate) AS ClickedDate
FROM (
SELECT otherCol1,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
解决方法
您可以聚合而无需子查询:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。