SQL:如何 select 区分某些列

SQL: How to select distinct on some columns

我有一个 table 看起来像这样:

+---+------------+----------+
|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
+---+------------+----------+

我想提取 SomeNumber 出现多于一个的行,并且 SomeNumbersSomeText 是不同的。这意味着我想要以下内容:

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

我不知道在这里做什么。

我需要一些类似的东西:

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
)

有什么建议吗?

使用带有行号和计数行的 cte 可能会得到您需要的东西:

创建并填充示例 table(在您以后的问题中为我们省去这一步):

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');

查询:

;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

结果:

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