我在涉及3个表的查询时遇到了困难。我需要按部门名称分组每个部门的3个最新用户。这些组应按users.dateadded排序,以便具有最新活动的部门是第一个。用户可以存在于多个部门中,因此我使用的查找表只包含userID和deptID。我的表格如下。
部门 - depID |名称
用户 - userID | name | dateadded
DepUsers - depID | userID
我需要的输出是
接收
John Doe - 4/23/2010
比尔史密斯 - 4/22/2010
会计
史蒂夫琼斯 - 4/22/2010
John Doe - 4/21/2010
审计
史蒂夫琼斯 - 4/21/2010
比尔史密斯 - 4/21/2010
答案 0 :(得分:2)
这应该为您提供每个部门最后添加的3个用户(在SQL 2005中使用新的ROW_NUMBER函数):
select * from (select D.name, U.name, U.dateadded, ROW_NUMBER() over (PARTITION BY D.depID ORDER BY U.dateadded DESC) as ROWID from Department as D
join DepUsers as DU on DU.depID = D.depID
join Users as U on U.userID = DU.userID) as T
where T.ROWID <= 3
我并不完全明白你希望输出看起来如何,但我想这个结果集可以帮助你开始实现目标。
答案 1 :(得分:1)
试试这个:
WITH CTE AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY DepartmentName ORDER BY DateAdded DESC) AS RowNumber
,D.name AS DepartmentName
,U.name AS UserName
,U.dateadded AS DateAdded
FROM
DepUsers DU
INNER JOIN Users U
ON DU.userID = U.userID
INNER JOIN Department D
ON DU.depID = D.depID
)
SELECT
DepartmentName
,UserName
,DateAdded
FROM CTE
WHERE RowNumber <= 3
ORDER BY DepartmentName, DateAdded DESC