Thursday, March 22, 2012

DISTINCT doesnt seem to be working

Hi all,

I am using SQLEXPRESS 2005 and can't figure out why my SQL query is not working.

Select DISTINCT ads.clientid, ads.ad, ads.adid, ads.cost, ads.description, ads.bold, ads.info, ads.contact, ads.coupon, ads.logo, ads.map, ads.webpage, ads.weburl, tclients.clientname, tclients.clientphone, tclients.addNumber, tclients.addStreet, tclients.addsuite, tclients.addcity, tclients.addstate, tclients.addzipfrom tclients, adswhere tclients.clientid=ads.clientidAND AdActive=1ORDER BY COSTDESC

I expect only one row to be returned for each ads.clientid. However, every single record that matches the query is being returned, which results in multiple records with the same clientid.

This happens if it isads.clientid ortclients.clientid.

Martin

DISTINCT returns unique rows based on all columns in the query, not just the first column (clientid) that you've specified.|||

Ah - I'm glad it it working as intended and I am not going mad...

How would I go about getting what I wanted then? Just one clientid.

|||

Can't answer that.

You said what you wanted.

You showed the query you have and the columns that you want.

The two don't mix, or the distinct would have worked anyhow. You obviously have multiple records with the same clientid, and differing data. WHICH of the differing data would you like when a clientid has multiple?

Assuming your fingers have names (index,middle,ring,pinky,thumb), and your hands have names (left, right).

Please tell me the length of your finger on each hand. And I only want one 2 entries, one for each hand. And if you are left scratching your head, it's because the question doesn't match the data, and you can't answer it. If I said, tell me the length of the longest finger on each hand, NOW you can answer, or I could say tell me the length of your index finger on each hand, etc.

|||

Thanks for that post - it helped me realize what I am doing wrong in my query.

I assumed because I was ordering by COST that it would take the first record for each clientid. In your example, it would order all my fingers by length, then take the longest one from each hand.

Since I know this is not the case, I know have to figure out how to re-write the query.

|||

Motley,

This SEEMS to work, but I'm not a SQL expert, so I can't be sure it will in real data. Does it look good to you? The bolded part is what I added.

Select DISTINCT ads.clientid, ads.ad, ads.adid, ads.cost, ads.description, ads.bold, ads.info, ads.contact, ads.coupon, ads.logo, ads.map, ads.webpage, ads.weburl, tclients.clientname, tclients.clientphone, tclients.addNumber, tclients.addStreet, tclients.addsuite, tclients.addcity, tclients.addstate, tclients.addzipfrom tclients, adswhere tclients.clientid=ads.clientidAND AdActive=1AND costin (select max(ads.cost)from adsgroup by clientid)ORDER BY COSTDESC

No comments:

Post a Comment