| Author |
Topic |
|
Kotti
Posting Yak Master
129 Posts |
Posted - 2009-10-12 : 03:02:16
|
| Hi FriendsI had a table like this PostId BlogId UserId1 1 12 2 23 1 14 4 85 6 36 4 8What i need is ,I need the top 3 last added distinct Blogid order by the PostId descOut Put :PostId BlogId userId6 4 85 6 33 1 1I need the Out put Like above result.Please help me or guide me to do this.Thanks in Advance |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2009-10-12 : 03:47:33
|
[code]DECLARE @Sample TABLE ( PostID INT, BlogID INT, UserID INT )INSERT @SampleSELECT 1, 1, 1 UNION ALLSELECT 2, 2, 2 UNION ALLSELECT 3, 1, 1 UNION ALLSELECT 4, 4, 8 UNION ALLSELECT 5, 6, 3 UNION ALLSELECT 6, 4, 8SELECT PostID, BlogID, UserIDFROM ( SELECT PostID, BlogID, UserID, ROW_NUMBER() OVER (PARTITION BY BlogID ORDER BY PostID DESC) AS recID FROM @Sample ) AS dWHERE recID = 1ORDER BY PostID DESC[/code] N 56°04'39.26"E 12°55'05.63" |
 |
|
|
jason97m
Starting Member
4 Posts |
Posted - 2009-10-12 : 03:49:40
|
| Hello, In order to accomplish what you desire, I would recommend the following SQL query:SELECT postid, blogid FROM yourtablename WHERE EXISTS (SELECT DISTINCT PostId FROM yourtablename) ORDER BY PostId DESC LIMIT 3Hope this recursive relationship query helps out.Jason MorrisBRIXTON.US |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2009-10-12 : 03:52:20
|
quote: Originally posted by jason97m SELECT postid, blogid FROM yourtablename WHERE EXISTS (SELECT DISTINCT PostId FROM yourtablename) ORDER BY PostId DESC LIMIT 3
And that is a Microsoft SQL Server query? N 56°04'39.26"E 12°55'05.63" |
 |
|
|
Kotti
Posting Yak Master
129 Posts |
Posted - 2009-10-12 : 05:24:44
|
| Hello Peso and Jason.Thanks for your reply.Peso,I am getting error when i execute your query as 'ROW_NUMBER' is not a recognized function name.Jason.I am getting error on LIMIT when i execute your query.Thanks |
 |
|
|
bklr
Master Smack Fu Yak Hacker
1693 Posts |
Posted - 2009-10-12 : 07:19:57
|
| see this linkhttp://sqlblogcasts.com/blogs/madhivanan/archive/2008/09/12/return-top-n-rows.aspx |
 |
|
|
rocknpop
Posting Yak Master
201 Posts |
Posted - 2009-10-12 : 07:59:15
|
| Are you using Sql 2000? On the same lines as Peso's reply:SELECT PostID, BlogID, UserIDFROM @SAMPLE S WHERE S.PostID NOT IN ( SELECT S1.PostID FROM @Sample S1 INNER JOIN @Sample S2 ON S1.BlogID = S2.BlogID WHERE S1.PostID < S2.PostID ) ORDER BY PostID DESC--------------------Rock n Roll with SQL |
 |
|
|
Kotti
Posting Yak Master
129 Posts |
Posted - 2009-10-12 : 10:44:18
|
quote: Originally posted by rocknpop Are you using Sql 2000? On the same lines as Peso's reply:SELECT PostID, BlogID, UserIDFROM @SAMPLE S WHERE S.PostID NOT IN ( SELECT S1.PostID FROM @Sample S1 INNER JOIN @Sample S2 ON S1.BlogID = S2.BlogID WHERE S1.PostID < S2.PostID ) ORDER BY PostID DESC--------------------Rock n Roll with SQL
Hi Yes i am using sql server 2000 and Thanks for your help.I am getting answer.Thanks for all. |
 |
|
|
|