【发布时间】:2016-06-14 12:54:39
【问题描述】:
我有以下查询,它返回我需要的数据:
SELECT SLCA.CustomerAccountNumber, SLCD.DefaultEmail, SOR.DocumentDate, SLST.*
FROM SLCustomerAccount AS SLCA
INNER JOIN SOPOrderReturn AS SOR ON SOR.CustomerID = SLCA.SLCustomerAccountID
INNER JOIN SLCustomerContactDefaultsVw AS SLCD ON SLCD.SLCustomerAccountID = SLCA.SLCustomerAccountID
LEFT OUTER JOIN MMS182SLStatus AS SLST ON SLST.Customer = SLCA.SLCustomerAccountID
WHERE SLCD.IsDefaultRole = 1 AND SLCD.DefaultEmail IS NOT NULL AND SLCD.DefaultEmail <> ''
AND SLCD.DefaultEmail = '...major@live.co.uk'
AND SLST.[Status] IS NULL
ORDER BY SOR.DocumentDate DESC
唯一的问题是,我在 where 过滤器中使用的这封电子邮件会产生多个这样的结果(尽管是正确的):
如何使用group by 删除重复的行,这样我只能得到最近 DocumentDate 的一条记录?
我知道我可以做到TOP 1,但这不是我需要的。因为,我现在通过将范围限定为具有重复的特定电子邮件来测试查询。稍后,我需要对所有没有这行 AND SLCD.DefaultEmail = '...major@live.co.uk' 的记录运行此查询 - 这样您就可以看到为什么我不能使用 TOP 1。
当我尝试像这样使用group by 时:
SELECT MAX(SLCA.CustomerAccountNumber), MAX(SLCD.DefaultEmail), MAX(SOR.DocumentDate), MAX(SLST.MMS182SLStatus), MAX(SLST.Customer), MAX(SLST.[Status])
FROM SLCustomerAccount AS SLCA
INNER JOIN SOPOrderReturn AS SOR ON SOR.CustomerID = SLCA.SLCustomerAccountID
INNER JOIN SLCustomerContactDefaultsVw AS SLCD ON SLCD.SLCustomerAccountID = SLCA.SLCustomerAccountID
LEFT OUTER JOIN MMS182SLStatus AS SLST ON SLST.Customer = SLCA.SLCustomerAccountID
WHERE SLCD.IsDefaultRole = 1 AND SLCD.DefaultEmail IS NOT NULL AND SLCD.DefaultEmail <> ''
AND SLCD.DefaultEmail = '...major@live.co.uk'
AND SLST.[Status] IS NULL
GROUP BY SLCD.DefaultEmail
ORDER BY MAX(SOR.DocumentDate) DESC
返回错误的结果:
我期待它返回这条记录:
有什么想法我在这里可能做错了吗?
【问题讨论】:
标签: sql sql-server group-by relational-database sql-order-by