如何使用PIVOT将EAV模式转换为普通模式?

时间:2019-12-11 13:06:44

标签: sql sql-server tsql pivot entity-attribute-value

我有一个名为SourceTable的表,其中有4个字段。 Properties_title字段具有3个值(AAA,BBB,CCC),但也可以有更多值。 NumericValue字段和Property_item_title字段各有一个值。根据下表,如果Properties_title是AAA或CCC,则Property_item_title就有值如果Properties_title是BBB,那么NumericValue就有价值。 现在,我想将其枢纽化为每个W_ID仅排一行,例如结果表

SourceTable

+--------+------------------+---------------+---------------------+
|  W_ID  | Properties_title | NumericValue  | Property_item_title |
+--------+------------------+---------------+---------------------+
| 102859 |     AAA          | null          |  Useless            |
| 102859 |     BBB          | 30000         |  null               |
| 102859 |     CCC          | null          |  Repair             |
| 92527  |     AAA          | null          |  Use                |
| 92527  |     BBB          | 3250          |  null               |
+--------+------------------+---------------+---------------------+

结果表:

+-------+-----------+---------+---------+
|  W_id |   AAA     |  BBB    | CCC     |
+-------+-----------+---------+-------- +
|102859 |  Useless  | 30000   |  Repair |
|92527  |  Use      | 3250    |  null   |
|...    |    ...    | ...     |  ...    |
+-------+-----------+---------+---------+
  

列名必须是动态的

我的代码:

CREATE TABLE dbo.SourceTable (W_ID int NOT NULL,
                            Properties_title varchar(3) NOT NULL,
                            NumericValue int NULL,
                            Property_item_title varchar(100) NULL);

INSERT INTO dbo.SourceTable
VALUES (102859,'AAA',NULL,'Useless'),
       (102859,'BBB',30000,NULL),
       (102859,'CCC',NULL,'Repair'),
       (92527,'AAA',NULL,'Use'),
       (92527,'BBB',3250,NULL);

SELECT *
FROM dbo.SourceTable;

Here是db <>小提琴。

谢谢您的帮助。

1 个答案:

答案 0 :(得分:2)

要遍历列的固定列,可以进行条件聚合:

select 
    w_id,
    max(case when properties_title = 'AAA' then property_item_title end) aaa,
    max(case when properties_title = 'BBB' then numeric_value end) bbb,
    max(case when properties_title = 'CCC' then property_item_title end) ccc
from sourcetable
group by w_id