Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Select distinct values

Author  Topic 

MariusC
Starting Member

16 Posts

Posted - 2014-06-25 : 06:31:57
Hello guys,

I have a problem when selecting distinct values from a table. I want to select those distinct numbers with a code that I want. To make it more clear i`ll show it on an example.
I have the following table:

tel_no | code | id_res
+-----------+--------------+-----------
0742062141 | a-not answer | 1
0742062141 | a-not answer | 2
0742062141 | c-answer | 3
0754231456 | a-not answer | 4
0754231456 | a-not answer | 5

When I use the following query it returns the distinct number but with the first code it finds:

select a.* from test_funnel as a
inner join
( select distinct tel_no,MIN(id_res) as id_res
from test_funnel
group by tel_no) as b
on
a.tel_no=b.tel_nol and a.id_res=b.id_res

tel_no | code | id_res
+-----------+--------------+----------
0742062141 | a-not answer | 1
0754231456 | a-not answer | 4

The result I want is this:

tel_no | code | id_res
+-----------+--------------+----------
0742062141 | c-answer | 3
0754231456 | a-not answer | 4

Please help!

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2014-06-25 : 06:36:26
change min() to max() and btw. you don't need distinct because you are using group by.


Too old to Rock'n'Roll too young to die.
Go to Top of Page

Ifor
Aged Yak Warrior

700 Posts

Posted - 2014-06-25 : 06:44:00
or

-- *** Test Data ***
CREATE TABLE #t
(
tel_no varchar(20) NOT NULL
,code varchar(20) NOT NULL
,id_res int NOT NULL
);
INSERT INTO #t
SELECT '0742062141', 'a-not answer', 1
UNION ALL SELECT '0742062141', 'a-not answer', 2
UNION ALL SELECT '0742062141', 'c-answer', 3
UNION ALL SELECT '0754231456', 'a-not answer', 4
UNION ALL SELECT '0754231456', 'a-not answer', 5;
-- *** End Test Data ***

WITH PhoneOrder
AS
(
SELECT tel_no, code, id_res
,ROW_NUMBER() OVER (PARTITION BY tel_no ORDER BY code DESC, id_res) AS rn
FROM #t
)
SELECT tel_no, code, id_res
FROM PhoneOrder
WHERE rn = 1;

Go to Top of Page

MariusC
Starting Member

16 Posts

Posted - 2014-06-25 : 06:45:29
That worked :D

Thanks very much!
Go to Top of Page
   

- Advertisement -