我有这个查询从我的数据库中返回重复的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
答案 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;