取得oracle中大集合的第一个唯一值

时间:2018-08-30 16:40:03

标签: sql oracle greatest-n-per-group

我有一个很大的集合,但是我只想获取特定列(c.id)的每个集合的第一个唯一值。

到目前为止,它已经可以工作了。但是我需要为每个不同的c.ID获得1条记录,因为现在我得到了多个c.ID,我只想忽略它,而只需将UNIQUE或FIRST值设置为c.ID

Select
    s.room,
    s.EXPRESSION,
    c.ID,
    c.COURSE_NAME,
    s.ROOM,
    t.FIRST_NAME,
    t.LAST_NAME,
    std.GRADE_LEVEL,
    CASE s.SCHOOLID
        WHEN 300 THEN 'MiddleSchool'
        WHEN 400 THEN 'UpperSchool'
        WHEN 200 THEN 'LowerSchool'
        WHEN 100 THEN 'ECC'
        ELSE 'miau'
        END AS "School"
  from   sections s
  INNER JOIN COURSES c ON s.COURSE_NUMBER=c.COURSE_NUMBER
  INNER JOIN TEACHERS t ON s.TEACHER=t.ID
  INNER JOIN CC co ON s.ID=co.SECTIONID
  INNER JOIN STUDENTS std ON std.ID = co.STUDENTID
  WHERE s.TERMID IN (2800, 2801, 2803, 2804)
  AND t.LAST_NAME='Dilworth' 

谢谢。

2 个答案:

答案 0 :(得分:0)

您如何称呼“第一”?关系数据库中表中的行就像篮子里的球一样。除非您应用一个命令,否则没有“命令”。

您所说的方式,您实际上并不关心它是哪一种,所以-取其中的任何一种。一种简单的方法是使用聚合函数之一(例如MIN)并将其他所有内容放入GROUP BY子句中,例如

select
  s.room,
  s.expression,
  min(c.ID) max_id
from ...
where ...
group by s.room, 
         s.expression;

答案 1 :(得分:0)

with data as (
    Select s.room, s.EXPRESSION, c.ID, c.COURSE_NAME, /* s.ROOM why twice? */,
        t.FIRST_NAME, t.LAST_NAME, std.GRADE_LEVEL,
        CASE s.SCHOOLID
            WHEN 300 THEN 'MiddleSchool'
            WHEN 400 THEN 'UpperSchool'
            WHEN 200 THEN 'LowerSchool'
            WHEN 100 THEN 'ECC'
            ELSE 'miau'
        END AS "School",
        row_number() over (partition by c.ID order by ??) as rn /* which is first? */
    from sections s
        INNER JOIN COURSES c ON s.COURSE_NUMBER = c.COURSE_NUMBER
        INNER JOIN TEACHERS t ON s.TEACHER = t.ID
        INNER JOIN CC co ON s.ID = co.SECTIONID
        INNER JOIN STUDENTS std ON std.ID = co.STUDENTID
    WHERE s.TERMID IN (2800, 2801, 2803, 2804) AND t.LAST_NAME = 'Dilworth'
)
select * from data where rn = 1;