1

如果我运行此查询以获取登录到每台计算机的用户列表:

SELECT
    T0.Computer,
    T4.[User],
    T4.[Last Modified]
    FROM Table1 T0
    LEFT OUTER JOIN Table4 T4 ON T0.Guid = T4.Guid
    Where T4.[Last Modified] >= getdate()-30 -- Logged in the last 30 days
    ORDER BY T4.[Last Modified] DESC

我得到:

Computer     User    Last Modified
--------     -----   --------------
Comp1        UserA   2013-07-14 16:31:59.000
Comp1        UserB   2013-06-03 13:43:32.000
Comp1        UserC   2013-04-28 15:58:22.000
Comp2        UserD   2013-04-28 11:10:21.000
Comp2        UserE   2013-04-19 15:01:33.000
Comp3        UserF   2013-04-18 08:01:03.000

我想显示 MAX([Last Modified]) 以仅显示登录每台计算机的最后一个用户:

Computer     User
--------     -----
Comp1        UserA
Comp2        UserD
Comp3        UserF

说 SELECT DISTINCT Computer, User ORDER BY [Last Modified] DESC 是有道理的,但是如果没有在 SELECT 中指定它就不能使用 ORDER BY。

并且 MAX([Last Modified]) 仅在用户不在 SELECT 中时才有效。


谢谢@拉马克

是否可以透视结果以显示最后两个用户?我们可以将行号更改为 User1、User2 等:

RN = 'User' + CAST(ROW_NUMBER() OVER(PARTITION BY T0.Name ORDER BY T4.[Last Modified] DESC) AS VarChar)

那么结果可能会显示:

Computer    User1     User2
--------    -----     -----
Comp1       UserA     UserB
Comp2       UserD     UserE
Comp3       UserF     NULL or ''
4

1 回答 1

7

您可以执行以下操作:

;WITH CTE AS
(
    SELECT  T0.Computer,
            T4.[User],
            T4.[Last Modified],
            RN = ROW_NUMBER() OVER(PARTITION BY T0.Computer ORDER BY T4.[Last Modified] DESC)
    FROM Table1 T0
    LEFT OUTER JOIN Table4 T4 
        ON T0.Guid = T4.Guid
    WHERE T4.[Last Modified] >= GETDATE()-30 -- Logged in the last 30 days
)
SELECT Computer, [User], [Last Modified]
FROM CTE
WHERE RN = 1

更新

试试这个以满足您的新要求:

;WITH CTE AS
(
    SELECT  T0.Computer,
            T4.[User],
            T4.[Last Modified],
            RN = ROW_NUMBER() OVER(PARTITION BY T0.Computer ORDER BY T4.[Last Modified] DESC)
    FROM Table1 T0
    LEFT OUTER JOIN Table4 T4 
        ON T0.Guid = T4.Guid
    WHERE T4.[Last Modified] >= GETDATE()-30 -- Logged in the last 30 days
)
SELECT  Computer, 
        MIN(CASE WHEN RN = 1 THEN [User] END) User1,
        MIN(CASE WHEN RN = 2 THEN [User] END) User2
FROM CTE
WHERE RN <= 2
GROUP BY Computer
于 2013-04-11T20:18:52.147 回答