这是我目前的查询:
SELECT
u.UserName, s.StatusName
FROM
UserStatus us
JOIN Status s on s.StatusId = us.StatusID
JOIN Users u on u.UserId = us.UserId
WHERE
us.UserId in (select UserId from Users)
AND us.DateCreated > '2017-07-14 00:00:00.000'
ORDER BY
us.DateCreated desc
它返回:
我如何才能获得每个用户的最新状态?
修改
我不能SELECT TOP 2
,因为我不知道会有多少用户。可能有500个。可能有10个。
答案 0 :(得分:2)
您可以在创建日期的位置设置每个用户的最大值 喜欢这个
SELECT
u.UserName, s.StatusName
FROM
UserStatus us
JOIN Status s on s.StatusId = us.StatusID
JOIN Users u on u.UserId = us.UserId
WHERE
us.UserId in (select UserId from Users)
AND us.DateCreated = (SELECT MAX(DateCreated) FROM UserStatus us2 WHERE
us2.UserId = us.UserId)
ORDER BY
us.DateCreated desc
答案 1 :(得分:0)
尝试更改
SELECT
u.UserName, s.StatusName
到
SELECT TOP(2)
u.UserName, s.StatusName
那应该只选择前两行! 见https://www.w3schools.com/sql/sql_top.asp
编辑:如果顶行更改,可以根据总状态的百分比进行选择