使用DISTINCT MAX的数据过多

时间:2019-05-17 13:37:41

标签: sql max sql-server-2014 distinct multiple-select

我想查看每个手机以及使用该手机的用户的最新活动。我有一个表格UserSessions,其中存储了特定用户的最新活动以及他们在该活动中使用的手机。大约有40部手机,但是我总是回想起太多的记录,例如当我只想要每部手机的最后一个活动时,就会有10,000行。我在做什么错了?

SELECT DISTINCT MAX(UserSessions.LastActivity), Handsets.Name,Users.Username
FROM UserSessions
INNER JOIN Handsets on Handsets.HandsetId = UserSessions.HandsetId
INNER JOIN Users on Users.UserId = UserSessions.UserId 
WHERE 
Handsets.Name in (1000,1001.1002,1003,1004....)
AND Handsets.Deleted = 0
GROUP BY UserSessions.LastActivity, Handsets.Name,Users.Username 

我希望每部手机都能获得该用户上次使用该手机的记录。我得到的是所有手机上的多条记录,日期超过10000行

2 个答案:

答案 0 :(得分:0)

除了那些作为设置函数的参数的列之外,您通常GROUP BYSELECT相同的列。

GROUP BY不返回重复项,因此不需要SELECT DISTINCT

SELECT MAX(UserSessions.LastActivity), Handsets.Name, Users.Username
FROM UserSessions
INNER JOIN Handsets on Handsets.HandsetId = UserSessions.HandsetId
INNER JOIN Users on Users.UserId = UserSessions.UserId 
WHERE Handsets.Name in (1000,1001.1002,1003,1004....)
  AND Handsets.Deleted = 0
GROUP BY Handsets.Name, Users.Username 

答案 1 :(得分:0)

没有DISTINCT MAX这样的东西。您拥有SELECT DISTINCT,可确保SELECT中引用的所有列都不会在多行中重复(作为一个组)。还有MAX()个聚合函数。

请注意:SELECT DISTINCT几乎永远不适用于GROUP BY

您似乎想要:

SELECT *
FROM (SELECT h.Name, u.Username, MAX(us.LastActivity) as last_activity,
             RANK() OVER (PARTITION BY h.Name ORDER BY MAX(us.LastActivity) desc) as seqnum
      FROM UserSessions us JOIN
           Handsets h
           ON h.HandsetId = us.HandsetId INNER JOIN
           Users u
           ON u.UserId = us.UserId 
      WHERE h.Name in (1000,1001.1002,1003,1004....) AND
            h.Deleted = 0
      GROUP BY h.Name, u.Username 
     ) h
WHERE seqnum = 1