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新手。所以如果有人能解释这个查询发生了什么,我将不胜感激。谢谢
答案 0 :(得分:2)
基本上,他使用3个select语句(每个属性1个)和UNION
将它们组合在一起,以形成一个公共表表达式,以便为每个employees属性获取行。
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