开发者

How to get Top 25 records order by createdon using SQL query?

开发者 https://www.devze.com 2023-02-12 22:52 出处:网络
I have two tables Like updatetext and users I want to top distinct records from updatetext.. Table User having unique records realated to user information and updatetext having multiple updatetext rec

I have two tables Like updatetext and users I want to top distinct records from updatetext.. Table User having unique records realated to user information and updatetext having multiple updatetext records... I want to get top latest update from updatetext table.. How I can get?

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

User

userid  username    password    
535 abhi        
540 shankar     
44  dhaval      
20  john        

I want to get top createdon records from UpdateText Table and get username and password from Users table.. Please help me.


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

Maybe you are searching for something like this?


This is top 25, latest update per user. I'm guessing this is what you really mean

;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


Not sure if I understand completely, but try something like:

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

精彩评论

暂无评论...
验证码 换一张
取 消