SQL:如何在某些列上选择distinct

时间:2016-12-23 13:06:26

标签: sql sql-server qsqlquery

我的桌子看起来像这样:

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

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

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

创建并填充样本表(在将来的问题中保存此步骤):

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