Link to home
Start Free TrialLog in
Avatar of huang_ck
huang_ck

asked on

sql server query to select the latest records with distinct

I have a sql server query:

SELECT DISTINCT
                          image_id, id, diy_variables, publish, upload_date, frame, member_id
FROM            table1
ORDER BY id DESC

I need to select the latest 10 records and I tried:
SELECT TOP 10 (DISTINCT image_id, id, diy_variables, publish, upload_date, frame, member_id) .....
SELECT TOP 10 DISTINCT image_id, id, diy_variables, publish, upload_date, frame, member_id .....

both doesnt work, what is the correct syntax to do so? Isn't it something like SELECT TOP 10 * ......
Avatar of QPR
QPR
Flag of New Zealand image

order by the upload_date
you can then get the 10 latest (or earliest)
or
select top 10 * from
(select distinct blah blah from tableName order by upload_date)
order by id desc
SELECT top 10 image_id, id, diy_variables, publish, upload_date, frame, member_id
FROM            table1
group by image_id, id, diy_variables, publish, upload_date, frame, member_id
ORDER BY id DESC
Avatar of huang_ck
huang_ck

ASKER

tried but both doesnt work. Guru, the query says it has syntax error. HuyBD, no syntax error but it doesnt selects out the distinct ones, the result is just same a normal select top 10 *....
huang_ck! what is field you want to select distinct, all or only one field
sorry guys, my query was a bit wrong, actually i want to select the latest top 10 group by image_id, in mysql I would write like this:

SELECT image_id, id, diy_variables, publish, upload_date, frame, member_id
FROM            table1
group by image_id
ORDER BY id DESC
limit 10

in sql server the syntax isn't like this, but the above i tried doesn't work, I need to know a way of getting the top 10 latest unique records group by image_id, I just dont know how. These doesnt work too:

SELECT   top 10  image_id, id, diy_variables, publish, upload_date, frame, member_id
FROM            table1
GROUP BY  image_id

SELECT top 10 image_id, id, diy_variables, publish, upload_date, frame, member_id
FROM            table1
group by image_id
ORDER BY id DESC
ASKER CERTIFIED SOLUTION
Avatar of HuyBD
HuyBD
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
cool, thats what i needed