2015-12-08 177 views
0

我與隨時間而改變,但保留版本屬性的列表工作,所以這裏有一個粗略的想法,我們正在尋找什麼(用ID是主鍵):SQL數據透視表值

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做一個數據透視表,但只能選擇最近的AttributeValue,其中Modified是max。 ID是該屬性列表的主要查找。 AttributeID是數據庫中該行的唯一GUID(已更改爲int)。

我該如何創建這種格式的數據透視表?

ID DocName   Category Owner 
--- ---------------- ---------- -------- 
100 Updated Document Regulatory Jane Doe 

還有其他幾百個我最終需要添加的屬性名稱,但這是一個簡明的例子。我也願意爲此更快/更好的想法。

回答

1

一種選擇是使用條件與聚集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 
+0

這似乎並不與PL/SQL的Oracle 11g的工作。在Rank()之前,我收到有關FROM語句未出現在「SELECT *」後的預期位置的錯誤。 – Taylor

+0

想通了 - 它不喜歡select *,但那很好 - 我只需要少量的列而不是所有的東西。乾杯! – Taylor