【问题标题】:How to display the related records in a single row in Oracle SQL?如何在Oracle SQL 中单行显示相关记录?
【发布时间】:2020-03-30 21:17:49
【问题描述】:

我编写了一个连接两个表的查询,我得到了以下结果集:

SELECT emp.employee_id,
      dept.department_name, 
      dept.department_id                                    
FROM employee emp, 
    department dept                                
WHERE emp.department_id = dept.department_id;
Employee_ID Department  Department_ID
Mark        Sales          D1
Mark        Marketing      D2
Justin      Textiles       D3
Kimberley   (null)        (null) 

但是,我需要在输出下方显示一个名为“状态”的新字段。马克可以在两个部门工作,因此计数为“2”,状态为“Y”(显示任何一条记录都是好的) 。 Justin 只在一个部门工作,计数为 1,状态应为“N”。 Kimberley 在任何地方都不起作用,计数为 0,状态应为“N”。

预期输出:

Employee_ID  Department  Department_ID  Status
Mark          Sales          D1            Y
Justin        Textiles       D3            N
Kimberley      (null)       (null)         N

请帮忙。

【问题讨论】:

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


    【解决方案1】:

    我认为这可以使用group bykeep 子句和max 轻松实现,如下所示:

    SELECT emp.employee_id,
          Max(dept.department_name) keep (dense_rank first order by dept.department_id) as department_name,
          Max(dept.department_id) keep (dense_rank first order by dept.department_id) as department_id,
          case when count(1) > 1 then 'Y' else 'N' end as status                                   
    FROM employee emp 
         LEFT JOIN department dept ON emp.department_id = dept.department_id
    GROUP BY emp.employee_id;
    

    干杯!!

    【讨论】:

      【解决方案2】:

      我了解到您希望显示每个用户的第一个部门,并添加一个标志来指示该员工是否属于至少一个其他部门。

      你可以使用窗口函数:

      select 
          employee_id,
          department_name,
          department_id
          case when cnt <= 1 then 'N' else 'Y' end status
      from (
          select 
              emp.employee_id,
              dept.department_name, 
              dept.department_id,
              row_number() over(partition by emp.employee_id order by dept.department_id) rn,
              count(*) over(partition by emp.employee_id) cnt
          from 
              employee emp
              left join department dept on emp.department_id = dept.department_id
      ) t
      where rn = 1
      

      旁注:始终使用显式连接(使用 on 关键字)而不是老式的隐式连接(在 from 子句中使用逗号),其语法更难阅读和维护。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多