如何从查询中删除重复值
How to remove duplicate values from a query
我遇到以下问题,我需要从我查询的特定列中删除重复值。不删除!(ClassID)
SchoolNo
Schoolyear
Schoolgrade
Classname
ClassId
65432
2001
5
ab
441
65432
2001
5
cd
442
65432
2001
6
a
443
65432
2001
6
b
444
56838
2001
5
ab
445
56838
2001
5
cd
446
56838
2001
6
ab
445
56838
2001
6
ef
447
12726
2001
5
ms
448
12726
2001
6
ms
448
如果您查看 classId 的值,我会重复 class 个数字,因为有些特殊学校有时会将两个 class 两个年级放在一起。问题是我的查询只需要显示 1 classid 值。没有重复。因此,我们可以删除任何重复值的额外 class,并且只显示 5 年级。
换句话说,我的 table 最终应该是这样的。
SchoolNo
Schoolyear
Schoolgrade
Classname
ClassId
65432
2001
5
ab
441
65432
2001
5
cd
442
65432
2001
6
a
443
65432
2001
6
b
444
56838
2001
5
ab
445
56838
2001
5
cd
446
56838
2001
6
ef
447
12726
2001
5
ms
448
代码大致是这样的。
select schoolno,schoolyear,schoolgrade,classname,classId
from classgroup cg
我该如何处理?
也许你可以这样做:
select
first_value(schoolno) over w,
first_value(schoolyear) over w,
first_value(schoolgrade) over w,
first_value(classname) over w,
first_value(classId) over w
FROM
classgroup
WINDOW w AS (PARTITION BY schoolno, schoolyear, classId ORDER BY schoolgrade);
您按 schoolno
、schoolyear
和 classId
对数据进行分区,并按 schoolgrade
排序,然后只取每个分区的第一行。
注意:语法可能有点偏差,因为我无法测试它
试试这个
select cg1.* from classgroup cg1
left join classgroup cg2 on (cg1."ClassId"=cg2."ClassId" and cg1."Schoolgrade"<cg2."Schoolgrade")
where cg2."Schoolgrade" is null
输出:
我遇到以下问题,我需要从我查询的特定列中删除重复值。不删除!(ClassID)
SchoolNo | Schoolyear | Schoolgrade | Classname | ClassId |
---|---|---|---|---|
65432 | 2001 | 5 | ab | 441 |
65432 | 2001 | 5 | cd | 442 |
65432 | 2001 | 6 | a | 443 |
65432 | 2001 | 6 | b | 444 |
56838 | 2001 | 5 | ab | 445 |
56838 | 2001 | 5 | cd | 446 |
56838 | 2001 | 6 | ab | 445 |
56838 | 2001 | 6 | ef | 447 |
12726 | 2001 | 5 | ms | 448 |
12726 | 2001 | 6 | ms | 448 |
如果您查看 classId 的值,我会重复 class 个数字,因为有些特殊学校有时会将两个 class 两个年级放在一起。问题是我的查询只需要显示 1 classid 值。没有重复。因此,我们可以删除任何重复值的额外 class,并且只显示 5 年级。
换句话说,我的 table 最终应该是这样的。
SchoolNo | Schoolyear | Schoolgrade | Classname | ClassId |
---|---|---|---|---|
65432 | 2001 | 5 | ab | 441 |
65432 | 2001 | 5 | cd | 442 |
65432 | 2001 | 6 | a | 443 |
65432 | 2001 | 6 | b | 444 |
56838 | 2001 | 5 | ab | 445 |
56838 | 2001 | 5 | cd | 446 |
56838 | 2001 | 6 | ef | 447 |
12726 | 2001 | 5 | ms | 448 |
代码大致是这样的。
select schoolno,schoolyear,schoolgrade,classname,classId
from classgroup cg
我该如何处理?
也许你可以这样做:
select
first_value(schoolno) over w,
first_value(schoolyear) over w,
first_value(schoolgrade) over w,
first_value(classname) over w,
first_value(classId) over w
FROM
classgroup
WINDOW w AS (PARTITION BY schoolno, schoolyear, classId ORDER BY schoolgrade);
您按 schoolno
、schoolyear
和 classId
对数据进行分区,并按 schoolgrade
排序,然后只取每个分区的第一行。
注意:语法可能有点偏差,因为我无法测试它
试试这个
select cg1.* from classgroup cg1
left join classgroup cg2 on (cg1."ClassId"=cg2."ClassId" and cg1."Schoolgrade"<cg2."Schoolgrade")
where cg2."Schoolgrade" is null
输出: