Monday, March 17, 2008

How do I have a select distinct and a top x in the same query

Ah, this one puzzled me. I had to go to the internet, and I still didn't quite get it. But, here is the solution.

SELECT
distinct top 3 y.*
FROM
(Select topicid, max(posted) as posted from yaf_Message Group by topicid) y

Order By Posted DESC

How does it work?
Ok, the initial select defines the top values returned.
The From creates another table with only those values that I need. So, when the first select looks in the table, it is looking in a filtered table.

1 comment:

Parisa Jalili Marandi said...

Hello.
I have a question regarding c#.net programming.
Is it possible to develp an application which uses a sql server and run all from cd? If there is I would be thankful to know the solution. THanks.
parisa.j@gmail.com