oracle 不使用聚合函数删除重复项

rfbsl7qr  于 2023-03-17  发布在  Oracle
关注(0)|答案(3)|浏览(145)

因此,我尝试从SIS导出每个学生的种族,但遇到了麻烦,因为如果一个学生是多种族的,那么每个学生将有多行。通常,我会使用一些聚合函数来删除这些重复项,但是我把它放在一个插件中,系统不接受聚合函数。我想做的是把所有的多种族的孩子,放在一行,并命名为Multiracial,我必须在没有聚合函数的情况下完成,这是一个使用聚合函数的代码示例。

select DISTINCT
   
        Student_number,
            case 
                when min(sr.racecd) = max(sr.racecd) then min(sr.racecd) else 'Two or more races' 
End as races
from students
Group by...

输出如下所示:

Student_Number   races
5234             White
4343             Two or more races
4323             Asian....

有没有一种方法可以在没有聚合函数的情况下实现这一点,或者我遇到了障碍?

rggaifut

rggaifut1#

创建一个视图,然后用简单的插件查询它,而不是查询表。
例如:

create view simple_student as -- and then your query below
select DISTINCT
  Student_number,
  case when min(sr.racecd) = max(sr.racecd) 
       then min(sr.racecd)
       else 'Two or more races' 
  end as races
from students
group by ...

然后插件可以从simple_student而不是student导出数据。

wvt8vs2t

wvt8vs2t2#

可以使用分析函数:

SELECT student_number,
       CASE
       WHEN num_races = 1
       THEN racecd
       ELSE 'Two or more races'
       END as races
FROM   (
  SELECT student_number,
         racecd,
         ROW_NUMBER() OVER (PARTITION BY student_number ORDER BY racecd) AS rn,
         COUNT(DISTINCT racecd) OVER (PARTITION BY student_number) AS num_races
  FROM   students
)
WHERE  rn = 1;
jhdbpxl9

jhdbpxl93#

你可以对每个种族使用left join,将STUDENT_NUMBER中的null值替换为0,然后对所有的种族进行加法运算。如果结果等于实际的学生人数,那么它只是一个种族,你可以使用Coalesce()得到它。

WITH
    students (STUDENT_NUMBER, STUDENT_NAME, RACE) AS
        (
            Select 5234, 'Jack', 'White' From Dual Union All
            Select 4343, 'John', 'Black' From Dual Union All
            Select 4343, 'John', 'White' From Dual Union All
            Select 4323, 'Lee',  'Asian' From Dual 
        )

Select  DISTINCT s.STUDENT_NUMBER, 
        CASE WHEN Nvl(w.STUDENT_NUMBER, 0) + Nvl(b.STUDENT_NUMBER, 0) + Nvl(a.STUDENT_NUMBER, 0) = s.STUDENT_NUMBER
             THEN  COALESCE(w.RACE, b.RACE, a.RACE)
        ELSE 'Two or more races'
        END "RACES"
From students s
Left Join ( Select STUDENT_NUMBER, RACE 
            From students
            Where RACE = 'White' ) w ON(w.STUDENT_NUMBER = s.STUDENT_NUMBER)
Left Join ( Select STUDENT_NUMBER, RACE 
            From students
            Where RACE = 'Black' ) b ON(b.STUDENT_NUMBER = s.STUDENT_NUMBER)
Left Join ( Select STUDENT_NUMBER, RACE 
            From students
            Where RACE = 'Asian' ) a ON(a.STUDENT_NUMBER = s.STUDENT_NUMBER)

R e s u l t :
STUDENT_NUMBER RACES           
-------------- -----------------
          4323 Asian             
          4343 Two or more races 
          5234 White

没有聚合、没有分组、没有分析函数......只有左连接、Nvl()-s和一些数学知识。

相关问题