从重复数据库中选择除前1之外的所有数据

时间:2017-07-12 14:58:04

标签: sql-server

我有这个查询从我的数据库中返回重复的TIID号码:

SELECT 
    TIID, CIID
FROM 
    INST_TASKS
WHERE 
    CIID IN (SELECT CIID
             FROM INST_TASKS
             GROUP BY CIID
             HAVING COUNT(*) > 1)

以上代码返回此结果:

TIID    CIID
-------------
187831  80162
187836  80162
187838  80162
194628  80522
194629  80522
194630  80812
194631  80812
194632  80522
194633  81444
194634  81444
194635  80812
194636  81594
194637  81594
194638  81444
194639  81594
194640  81626
194641  81626
194642  81700
194643  81626
194644  81700
194645  81700

我想要做的是为每个TIID号码选择除{1}之外的CIID个数字。

所需的结果应为:

TIID    CIID
-------------
187836  80162
187838  80162
194629  80522
194632  80522
194631  80812
194635  80812
194634  81444
194638  81444
194637  81594
194639  81594
194641  81626
194643  81626
194644  81700
194645  81700

2 个答案:

答案 0 :(得分:1)

您可以使用Row_Number并按>过滤1如下:

Select * from (
   Select *, RowN = Row_Number() over(Partition by CIID Order by TIID)  from #yourtable ) a
where a.RowN > 1

输出如下:

+--------+-------+
|  TIID  | CIID  |
+--------+-------+
| 187838 | 80162 |
| 187836 | 80162 |
| 194632 | 80522 |
| 194629 | 80522 |
| 194635 | 80812 |
| 194631 | 80812 |
| 194638 | 81444 |
| 194634 | 81444 |
| 194639 | 81594 |
| 194637 | 81594 |
| 194643 | 81626 |
| 194641 | 81626 |
| 194645 | 81700 |
| 194644 | 81700 |
+--------+-------+

答案 1 :(得分:1)

尝试此查询 -

;WITH CTE
AS (
    SELECT TIID
        ,CIID
        ,Row_Number() OVER (
            PARTITION BY CIID ORDER BY TIID
            ) AS RowNum
    FROM INST_TASKS
    )
SELECT TIID
    ,CIID
FROM CTE
WHERE RowNum > 1;