在 SQL 中的多个列中查找重复项
Find duplicates on multiple columns in a SQL
我想找到只有 subjectID(0,1,2) 的 batchID,请帮助我,在此先感谢
我需要回答 BatchID=12 和 BatchID=51,我可以在 sql
中做什么
我的表格
uid BatchID SubjectID
6 2 0
7 2 1
8 2 2
9 2 4
10 3 0
11 3 1
12 4 5
13 4 0
14 5 5
15 6 5
17 7 0
18 7 1
19 7 2
26 12 0
27 12 1
28 12 2
29 1 0
30 1 1
31 1 4
62 45 5
63 46 0
64 46 1
65 46 4
107 49 6
108 49 2
109 49 4
110 50 1
111 50 3
116 0 1
117 0 4
118 51 0
119 51 1
120 51 2
您可以为此使用条件聚合:
select batchId
from your_table
group by batchId
having count(distinct case when subjectID in (0,1,2) then subjectID end) = 3
and count(case when subjectID not in (0,1,2) then 1 end) = 0
解释:
Group by batchId
- 根据 batchId 聚合
count(distinct case when subjectID in (0,1,2) then subjectID end)
- 仅当所有三个都存在于此 batchId 时才生成 3
count(case when subjectID not in (0,1,2) then 1 end)
- 如果除了 0,1,2 之外没有其他 subjectID,则生成 0,假设 subjectId 列中不允许空值。
您可以使用 Row_Number()
;with cte as (
select *, RowN = row_number() over (partition by batchid order by uid) from #yourbatch where subjectid in (0,1,2)
) select distinct BatchId from cte where RowN > 1
我想找到只有 subjectID(0,1,2) 的 batchID,请帮助我,在此先感谢
我需要回答 BatchID=12 和 BatchID=51,我可以在 sql
中做什么我的表格
uid BatchID SubjectID
6 2 0
7 2 1
8 2 2
9 2 4
10 3 0
11 3 1
12 4 5
13 4 0
14 5 5
15 6 5
17 7 0
18 7 1
19 7 2
26 12 0
27 12 1
28 12 2
29 1 0
30 1 1
31 1 4
62 45 5
63 46 0
64 46 1
65 46 4
107 49 6
108 49 2
109 49 4
110 50 1
111 50 3
116 0 1
117 0 4
118 51 0
119 51 1
120 51 2
您可以为此使用条件聚合:
select batchId
from your_table
group by batchId
having count(distinct case when subjectID in (0,1,2) then subjectID end) = 3
and count(case when subjectID not in (0,1,2) then 1 end) = 0
解释:
Group by batchId
- 根据 batchId 聚合
count(distinct case when subjectID in (0,1,2) then subjectID end)
- 仅当所有三个都存在于此 batchId 时才生成 3
count(case when subjectID not in (0,1,2) then 1 end)
- 如果除了 0,1,2 之外没有其他 subjectID,则生成 0,假设 subjectId 列中不允许空值。
您可以使用 Row_Number()
;with cte as (
select *, RowN = row_number() over (partition by batchid order by uid) from #yourbatch where subjectid in (0,1,2)
) select distinct BatchId from cte where RowN > 1