Thursday, March 8, 2012

COMPLEX sql query PLEASE HELP!

I cant get "order by" to work in this sql query..
I use this query:

"SELECT DISTINCT TOP 12 name,total = COUNT(*) FROM products where kat = 'music' group by namn"
and I want to add this some where to get 12 random records: "ORDER BY NewID()"

I tried this:"SELECT DISTINCT TOP 12 name,total = COUNT(*) FROM products where kat = 'music' group by namn ORDER BY NewID()""
but get the error:
"ORDER BY items must appear in the select list if SELECT DISTINCT is specified"

I can′t figure out how I should write the query..
Somebody have any ideas??
/Radiwoi

Try something like this:
SELECT TOP 12 name, total FROM (SELECT name, total = COUNT(*) FROM products WHERE kat = 'music' GROUP BY name) AS groupedSet ORDER BY NEWID()

The subquery generates a set in the output format that you want, the main query just orders it randomly and restricts it to 12 rows.

Does this help?
|||Thanks for your answer and thanks for your help It worked perfect.
you are KING!!!

No comments:

Post a Comment