如何使用SQL查询创建排名前25的记录?

时间:2011-02-24 10:22:36

标签: sql-server sql-server-2005 sql

我有两个表像updatetext和用户我希望从updatetext中获得不同的记录。表用户具有与用户信息相关的唯一记录和具有多个updatetext记录的updatetext ...我想从updatetext表获得最新的最新更新。我怎么能得到?

Users Table
1) userid
2) username
3) password
4) createdon

UpdateText Table
1) updatetextID
2) userid
3) updateScrap
4) createdon
3) location

UpdateText

updatetextID    userid  updateScrap     Createdon
     11      535     yes good test      2/23/2011 9:59
     12      540    udpate sample       2/23/2011 9:58
     13       44    Absas               2/22/2011 12:30
     14       20    test text 123       2/22/2011 12:24
     15      540    hi how are you?     2/22/2011 12:00
     16      535    Hi r u there?       2/22/2011 12:30
     17      540    welcome back        2/22/2011 10:23

用户

userid  username    password    
535 abhi        
540 shankar     
44  dhaval      
20  john        

我想从UpdateText Table获得最佳创建记录 从用户表中获取用户名和密码.. 请帮帮我。

3 个答案:

答案 0 :(得分:1)

这是前25名,每位用户的最新更新。我猜这就是你的意思

;WITH CTE AS
(
  SELECT
     *,
     ROW_NUMBER() OVER (PARTITION BY userid ORDER BY createdon) AS RankNum
  FROM
     [UpdateText]
)
SELECT TOP 25
   *
FROM
   CTE 
   JOIN
   Users U ON CTE.userid  = U.userid 
WHERE
   RankNum = 1
ORDER BY
   CTE.createdon

答案 1 :(得分:1)

SELECT  TOP 25 
        ut.*
        ,u.username
        ,u.password
FROM    [UpdateText] ut
JOIN    Users u ON  ut.userid = u.userid
JOIN    (   SELECT  MAX(ut2.createdon) as maxcreatedon
                    ,ut2.userid
            FROM    [UpdateText] ut2
            GROUP BY ut2.userid
        ) x ON x.maxcreatedon = ut.createdon
            AND x.userid = ut.userid
ORDER BY ut.createdon DESC

也许你正在寻找这样的东西?

答案 2 :(得分:0)

不确定我是否完全理解,但尝试类似:

SELECT * FROM UpdateText 
   INNER JOIN Users ON UpdateText.userid = Users.userid
ORDER BY UpdateText.createdon DESC LIMIT 25