如何对特定行执行分组

5m1hhzi4  于 2021-08-01  发布在  Java
关注(0)|答案(3)|浏览(276)

我正在运行以下查询以获取数据:

  1. SELECT DISTINCT student_id, student_name from class_students where city = 'foobar' and student_id <> 0;

我得到的数据如下:

  1. student_id | student_name
  2. ------------+----------------------------------------
  3. 41990 | James
  4. 48220 | John
  5. 00000 |
  6. 00000 | lkjkj
  7. 00000 | random name
  8. 00000 | somethingelse

我更想找回这些数据:

  1. student_id | student_name
  2. ------------+----------------------------------------
  3. 41990 | James
  4. 48220 | John
  5. 00000 | Name-doesnt-exist

也就是说把所有的 00000 一行中的名称 NA

9rnv2umw

9rnv2umw1#

  1. SELECT student_id, case when student_id = '00000' then 'N-A' else max(student_name) end
  2. from class_students
  3. where city = 'foobar'
  4. and student_id <> 0
  5. group by student_id
icomxhvb

icomxhvb2#

如果存在多个名称,则标记它。

  1. select student_id,
  2. case when count(distinct student_name) > 1 then 'N/A' else min(student_name) end as student_name
  3. from class_students
  4. where city = 'foobar' and student_id <> 0
  5. group by student_id

您还可以从结果中完全消除这些组:

  1. having count(distinct student_name) = 1
eoxn13cs

eoxn13cs3#

你可以试着用 row_number() ```
select student_id,coalesce(student_name,'Name-doesnt-exist') as name
from
(
SELECT student_id, student_name,row_number() over(partition by student_id order by case when student_name is null then 1 else 2 end) as rn
from class_students where city = 'foobar' and student_id <> 0
)A where rn=1

相关问题