SQL子查询问题

时间:2010-05-12 19:27:36

标签: sql sql-server

我有以下SQL

SELECT
    Seq.UserSessionSequenceID, 
    Usr.SessionGuid, 
    Usr.UserSessionID,
    Usr.SiteID, 
    Seq.Timestamp, 
    Seq.UrlTitle, 
    Seq.Url
FROM
    tblUserSession Usr
INNER JOIN  
    tblUserSessionSequence Seq ON Usr.UserSessionID = Seq.UserSessionID
WHERE     
    (Usr.Timestamp > DATEADD(mi, -45, GETDATE())) AND (Usr.SiteID = 15)
ORDER BY Usr.Timestamp DESC

非常简单的东西。在tblUserSessionSequence中本质上有多个UserSessionIDs行。我只想返回具有唯一UserSessionID的最新(前1)行。我该怎么做?

2 个答案:

答案 0 :(得分:4)

您可以使用窗口函数ROW_NUMBER为每个用户编号行,并仅选择行号为1的行。

SELECT
    UserSessionSequenceID, 
    SessionGuid, 
    UserSessionID,
    SiteID, 
    Timestamp, 
    UrlTitle, 
    Url
FROM (
    SELECT
        Seq.UserSessionSequenceID, 
        Usr.SessionGuid, 
        Usr.UserSessionID,
        Usr.SiteID, 
        Usr.Timestamp AS UsrTimestamp, 
        Seq.Timestamp, 
        Seq.UrlTitle, 
        Seq.Url,
        ROW_NUMBER() OVER (PARTITION BY Usr.UserSessionID
                           ORDER BY Seq.UserSessionSequenceID DESC) AS rn
    FROM
        tblUserSession Usr
    INNER JOIN  
        tblUserSessionSequence Seq ON Usr.UserSessionID = Seq.UserSessionID
    WHERE     
        (Usr.Timestamp > DATEADD(mi, -45, GETDATE())) AND (Usr.SiteID = 15)
) T1
WHERE rn = 1
ORDER BY UsrTimestamp DESC

答案 1 :(得分:0)

如果您希望在查询中只返回一行(即带有最新时间戳的ID),只需更改

SELECT

SELECT TOP 1

如果您希望为每个UserSessionID 获取单行,但是您希望确保获得具有最新TimeStamp的那一行,则会稍微复杂一些。

你可以这样做:

SELECT  
    Seq.UserSessionSequenceID,   
    Usr.SessionGuid,   
    Usr.UserSessionID,  
    Usr.SiteID,   
    Seq.Timestamp,   
    Seq.UrlTitle,   
    Seq.Url  
FROM  
    tblUserSession Usr  
INNER JOIN    
    (SELECT 
        UserSessionSequenceID, 
        UserSessionID, 
        Timestamp, 
        UrlTitle, 
        Url, 
        ROW_NUMBER() over (PARTITION BY UserSessionID ORDER BY UserSessionSequenceID) AS nbr

    FROM tblUserSessionSequence) Seq ON Usr.UserSessionID = Seq.UserSessionID AND Seq.nbr = 0
WHERE       
    (Usr.Timestamp > DATEADD(mi, -45, GETDATE())) AND (Usr.SiteID = 15)  
ORDER BY Usr.Timestamp DESC