【问题标题】:Can anyone explain this Query?谁能解释这个查询?
【发布时间】:2016-03-11 02:18:47
【问题描述】:
with a as (
select a.*, row_number() over (partition by department order by attributeID) rn
  from attributes a),
e as (
select employeeId, department, attribute1, 1 rn from employees union all
select employeeId, department, attribute2, 2 rn from employees union all
select employeeId, department, attribute3, 3 rn from employees
)
select e.employeeId, a.attributeid, e.department, a.attribute, a.meaning, 
   e.attribute1 as value 
 from e join a on a.department=e.department and a.rn=e.rn 
order by e.employeeId, a.attributeid

此查询由 Ponder Stibbons 编写,用于回答 this 问题。但是我对此感到头晕目眩,因为我完全不明白这里发生了什么。我是 SQL 新手。所以如果有人能解释这个查询发生了什么,我将不胜感激。谢谢你

【问题讨论】:

    标签: sql oracle plsql


    【解决方案1】:

    基本上,他使用 3 个 select 语句(每个属性 1 个)和 UNION 将它们一起取消透视数据,以创建一个公共表表达式,以便他获取每个员工属性的行。

    select employeeId, department, attribute1, 1 rn from employees union all
    select employeeId, department, attribute2, 2 rn from employees union all
    select employeeId, department, attribute3, 3 rn from employees
    

    他使用窗口函数为属性部门分配编号的另一个表。他稍后会使用这个数字来加入他的未透视数据。他发布了他的示例代码。

    select a.*, row_number() over (partition by department order by attributeID) rn
      from attributes a
    

    我建议您使用他提供的示例数据并运行以下命令。这将向您显示 CTE。我认为一旦你看到这些数据,它就会更有意义。

    with a as (
    select a.*, row_number() over (partition by department order by attributeID) rn
      from attributes a),
    e as (
    select employeeId, department, attribute1, 1 rn from employees union all
    select employeeId, department, attribute2, 2 rn from employees union all
    select employeeId, department, attribute3, 3 rn from employees
    )
    
    SELECT * from a
    SELECT * from e
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 2012-02-12
      • 1970-01-01
      • 2016-04-10
      • 2010-10-19
      相关资源
      最近更新 更多