Avatar of kneidels
kneidels asked on

Dictinct question

hey there

i have a simple MS Access table, and i always seem to have trouble qith distinct queries...

table images:

imageID -- imageName -- cat -- subcat -- uploadDate
---------------------------------------------------------------
1 -----------  test ---------- 2 ------ 5 ---------- 05/05/08
2 -----------  test2 --------- 2 ------ 7 ---------- 05/05/08
3 -----------  test3 --------- 2 ------ 6 ---------- 05/05/08
4 -----------  test4 --------- 2 ------ 5 ---------- 05/05/08
5 -----------  test5 --------- 2 ------ 5 ---------- 05/05/08

i would like to extract the top X records, but only one from each subcat - order by imageID DESC
so in the above example, i would want to  get all the fields , in rows 2, 3 and 5.

whatever i try i get Distinct errors.

any help?

thanks!
SQL

Avatar of undefined
Last Comment
kneidels

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
nexusnation

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
kneidels

thank - works great!
could you explain the logic behind it?

nexusnation

Sure.  More or less, you're selecting every record from images.

But, you're checking to make sure that record (identified by imageID) matches the rule you set: top record when sorted by image ID DESC.   I think you can understand all of that so far.  The catch is that if we were to just run "SELECT TOP 1 imageID FROM images ORDER BY imageID DESC", it'd return 1 EVERY TIME.

That's clearly not what we want -- we must only compare it to other imageIDs in the same subcategory.

Thus, we need to create a comparison that transcends across the the query and it's sub-query.  images.subcat represents the category of the current record, and making sure it is the same as images2.subcat allow us to compare it only to other imageIDs in the same subcategory.

The reason why we have to give images an alias is because we have to compare between the queries.  And we can't go saying images.subcat = images.subcat, because then the SQL engine has no idea what you're referring to.

Does that make sense?  It's kinda tough to explain.  I can take another crack at it if you need me to.
ASKER
kneidels

ok, i get it. hope to remember the principle for future use.

thanks again!
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy