Forum Moderators: open

Message Too Old, No Replies

Select distinct won't return distinct value

         

Mohamed

2:20 pm on Jun 6, 2006 (gmt 0)

10+ Year Member



I want select distinct field and return value of that field, but I have problem which is: select distinct returns duplicate value.

eg, I wan select distinct customer name and id from the customer table. one customer may have different cus_ids since cus_ids are auto increment and depend on the purchased items. so what I want is to select distinct customer name so that I can print customer name and customer id once.

code is here:

select distinct cus_name, cus_id from customers order by cus_name asc

ChadSEO

3:27 pm on Jun 6, 2006 (gmt 0)

10+ Year Member



Mohamed,

It's returning distinct rows - that is, distinct combinations of customer names and ids. In order to get what you want, you have to decide which customer id you want returned - the first or the last. The following query should work for you:

SELECT cus_name, max(cus_id) as cus_id FROM customers GROUP BY cus_name ORDER BY cus_name asc

This will return the last cus_id - if you want the first one, change max to min. Hope this helps!

Chad

Mohamed

3:51 pm on Jun 6, 2006 (gmt 0)

10+ Year Member



Thanks chad.

It works.

Mohamed