从查询中删除重复项

时间:2011-06-16 11:33:23

标签: sql-server

所以我有以下查询

SELECT r.userId, r.programmeId, u.email, u.firstName, u.lastName, u.profileId, tblProgrammes.name, u.storeId, r.dateEnded AS lastPass, r.dateExpired
FROM tblUserRepeatHistory AS r INNER JOIN
tblUsers AS u ON r.userId = u.id INNER JOIN
tblProgrammes ON r.programmeId = tblProgrammes.id
WHERE (r.dateExpired IS NOT NULL) AND (u.storeId = @storeId)
GROUP BY r.userId, r.programmeId, u.email, u.firstName, u.lastName, u.profileId, tblProgrammes.name, u.storeId, r.dateEnded, r.dateExpired, r.id
HAVING (DATEDIFF(D, MAX(r.dateExpired), GETDATE() + 31) >= 0)

返回以下数据

11 22 asdf@asdf.com store-mgr jamie2 1 Deli Food Service 1 5 04/02/2011 09:36:11 10/05/2011 09:36:11

11 22 asdf@asdf.com store-mgr jamie2 1 Deli Food Service 1 5 04/02/2011 09:36:11 10/05/2011 09:36:11

11 22 asdf@asdf.com store-mgr jamie2 1 Deli Food Service 1 5 11/05/2011 09:44:36 10/07/2011 09:44:36

11 23 asdf@asdf.com store-mgr jamie2 1 Deli Food Service 2 5 11/05/2011 10:12:50 16/06/2011 10:12:50

我基本上只为每个用户和程序返回了1条记录,其中最近添加的一条应该返回,所以我猜是MAX(dateExpired)。所以这个查询应该只返回两个记录

11 22 asdf@asdf.com store-mgr jamie2 1 Deli Food Service 1 5 11/05/2011 09:44:36 10/07/2011 09:44:36
11 23 asdf@asdf.com store-mgr jamie2 1 Deli Food Service 2 5 11/05/2011 10:12:50 16/06/2011 10:12:50

3 个答案:

答案 0 :(得分:0)

SELECT DISTINCT是您需要的SQL关键字。 DISTINCT导致查询仅返回不同的列

答案 1 :(得分:0)

从GROUP BY子句中删除r.dateExpired,并将其替换为选择列表中的“MAX(r.dateExpired)as dateExpired”。

答案 2 :(得分:0)

您可以使用交叉申请

SELECT * FROM tblUsers as u CROSS JOIN tblProgrammes p
CROSS APPLY
(SELECT TOP 1 dateExpired FROM tblUserRepeatHistory
WHERE userId = u.id and programmeId = p.id
ORDER BY dateExpired desc
) as rr

在共同相关的子查询中,您可以在tblUserRepeatHistory中获得最大dateExpired,其中符合程序和用户, 对于嵌套查询和表值函数,交叉应用就像内连接一样