SQL 枢轴 table 更新值
SQL Pivot table with updating values
我正在处理随时间变化但保留版本的属性列表,所以这里是我们正在查看的内容的粗略概念(ID 是主键):
ID ATTRIBUTENAME ATTRIBUTEVALUE CREATED MODIFIED AttributeID
--- ---------------- ------------------------------- ------------------ ------------------- ---
100 DocName Updated Document 10-JUL-15 08.40.12 10-JUL-15 08.40.12 06
100 Category Regulatory 10-JUL-15 08.40.12 10-JUL-15 08.40.12 05
100 Owner Jane Doe 10-JUL-15 08.40.12 10-JUL-15 08.40.12 04
100 DocName Test Document 10-JUL-15 08.40.12 10-JUL-15 01.10.30 03
100 Category Regulatory 10-JUL-15 08.40.12 10-JUL-15 01.10.30 02
100 Owner John Doe 10-JUL-15 08.40.12 10-JUL-15 01.10.30 01
我想对 DocName、Category 和 Owner 做一个透视,但只有 select 最近的 AttributeValue,其中 Modified 是最大的。 ID 是该属性列表的主要查找。 AttributeID 是数据库中该行的唯一 GUID(更改为 int)。
如何创建这种格式的数据透视表 table?
ID DocName Category Owner
--- ---------------- ---------- --------
100 Updated Document Regulatory Jane Doe
我最终需要添加数百个其他属性名称,但这是一个简明示例。我也愿意接受 faster/better 对此的想法。
一种选择是使用条件聚合 rank()
:
select id,
max(case when attributename = 'DocName' then attributevalue end) docname,
max(case when attributename = 'Category' then attributevalue end) Category,
max(case when attributename = 'Owner' then attributevalue end) Owner
from (
select *, rank() over (partition by id order by modified desc) rn
from yourtable ) t
where rn = 1
group by id
我正在处理随时间变化但保留版本的属性列表,所以这里是我们正在查看的内容的粗略概念(ID 是主键):
ID ATTRIBUTENAME ATTRIBUTEVALUE CREATED MODIFIED AttributeID
--- ---------------- ------------------------------- ------------------ ------------------- ---
100 DocName Updated Document 10-JUL-15 08.40.12 10-JUL-15 08.40.12 06
100 Category Regulatory 10-JUL-15 08.40.12 10-JUL-15 08.40.12 05
100 Owner Jane Doe 10-JUL-15 08.40.12 10-JUL-15 08.40.12 04
100 DocName Test Document 10-JUL-15 08.40.12 10-JUL-15 01.10.30 03
100 Category Regulatory 10-JUL-15 08.40.12 10-JUL-15 01.10.30 02
100 Owner John Doe 10-JUL-15 08.40.12 10-JUL-15 01.10.30 01
我想对 DocName、Category 和 Owner 做一个透视,但只有 select 最近的 AttributeValue,其中 Modified 是最大的。 ID 是该属性列表的主要查找。 AttributeID 是数据库中该行的唯一 GUID(更改为 int)。
如何创建这种格式的数据透视表 table?
ID DocName Category Owner
--- ---------------- ---------- --------
100 Updated Document Regulatory Jane Doe
我最终需要添加数百个其他属性名称,但这是一个简明示例。我也愿意接受 faster/better 对此的想法。
一种选择是使用条件聚合 rank()
:
select id,
max(case when attributename = 'DocName' then attributevalue end) docname,
max(case when attributename = 'Category' then attributevalue end) Category,
max(case when attributename = 'Owner' then attributevalue end) Owner
from (
select *, rank() over (partition by id order by modified desc) rn
from yourtable ) t
where rn = 1
group by id