SQL: How to select distinct on some columns

4.9k views Asked by At

I have a table looking something like this:

+---+------------+----------+
|ID | SomeNumber | SomeText |
+---+------------+----------+
|1  | 100        | 'hey'    |
|2  | 100        | 'yo'     |
|3  | 100        | 'yo'     | <- Second occurrence
|4  | 200        | 'ey'     |
|5  | 200        | 'hello'  |
|6  | 200        | 'hello'  | <- Second occurrence
|7  | 300        | 'hey'    | <- Single
+---+------------+----------+

I would like to extract the rows where SomeNumber appears more than ones, and SomeNumbers and SomeText are distinct. That means I would like the following:

+---+------------+----------+
|ID | SomeNumber | SomeText |
+---+------------+----------+
|1  | 100        | 'hey'    |
|2  | 100        | 'yo'     |
|4  | 200        | 'ey'     |
|5  | 200        | 'hello'  |
+---+------------+----------+

I don't know what to do here.

I need something along the lines:

SELECT t.ID, DISTINCT(t.SomeNumber, t.SomeText)  --this is not possible
FROM (
    SELECT mt.ID, mt.SomeNumber, mt.SomeText
    FROM MyTable mt
    GROUP BY mt.SomeNumber, mt.SomeText --can't without mt.ID
    HAVING COUNT(*) > 1
)

Any suggestions?

1

There are 1 answers

5
Zohar Peled On BEST ANSWER

Using a cte with row number and count rows might get you what you need:

Create and populate sample table (Please save us this step in your future questions):

CREATE TABLE MyTable(id int, somenumber int, sometext varchar(10));
INSERT INTO MyTable VALUES
(1,100,'hey'),
(2,100,'yo'),
(3,100,'yo'),
(4,200,'ey'),
(5,200,'hello'),
(6,200,'hello'),
(7,300,'hey');

The query:

;WITH cte as 
(
    SELECT id, 
           someNumber,
           someText, 
           ROW_NUMBER() OVER (PARTITION BY someNumber, someText ORDER BY ID) rn, 
           COUNT(id) OVER (PARTITION BY someNumber) rc
    FROM MyTable
)
SELECT id, someNumber, someText
FROM cte
WHERE rn = 1
AND rc > 1

Results:

id  someNumber  someText
1   100         hey 
2   100         yo  
4   200         ey  
5   200         hello