我有一个表,该表具有约80k行,格式如下:
+--------+-----------+-------------------+---------------------+----------------------+-----------------+----------------+-----------------+
| SiteID | SubSiteID | DynamicPropertyID | DynamicPropertyName | DynamicPropertyValue | StaticProperty1 | StaticPropety2 | StaticProperty3 |
+--------+-----------+-------------------+---------------------+----------------------+-----------------+----------------+-----------------+
| 1 | 1 | 1 | Property1 | ABC | 1 | 1 | 1 |
| 1 | 1 | 2 | Property2 | XYZ | 1 | 1 | 1 |
| 1 | 1 | 3 | Property3 | DEF | 1 | 1 | 1 |
| 1 | 2 | 1 | Property1 | GHT | 1 | 1 | 1 |
| 1 | 2 | 2 | Property2 | XYZ | 1 | 1 | 1 |
| 1 | 2 | 3 | Property3 | WWF | 1 | 1 | 1 |
| 2 | 1 | 1 | Property1 | FHS | 1 | 1 | 1 |
| 2 | 1 | 2 | Property2 | HHS | 1 | 1 | 1 |
| 2 | 1 | 3 | Property3 | BSF | 1 | 1 | 1 |
| 2 | 2 | 1 | Property1 | QDD | 1 | 1 | 1 |
| 2 | 2 | 2 | Property2 | FFF | 1 | 1 | 1 |
| 2 | 2 | 3 | Property3 | YTR | 1 | 1 | 1 |
+--------+-----------+-------------------+---------------------+----------------------+-----------------+----------------+-----------------+
我需要做的是为此表创建一个视图,该视图将表旋转为以下格式:
+--------+-----------+-----------+-----------+-----------+-----------------+-----------------+-----------------+
| SiteID | SubSiteID | Property1 | Property2 | Property3 | StaticProperty1 | StaticProperty2 | StaticProperty3 |
+--------+-----------+-----------+-----------+-----------+-----------------+-----------------+-----------------+
我面临的问题是,随着时间的推移,我们可能会在表中添加新的“动态属性”,因此,如果我们向表中添加Property4
,则视图必须能够动态更改以添加新列例如,每个SiteID / SubsiteID组合。
对此表示任何建议或帮助。
答案 0 :(得分:0)
请尝试以下查询:
DECLARE @samplex TABLE
(
SiteID INT,
SubSiteID INT,
DynamicPropertyID INT,
DynamicPropertyName VARCHAR(10),
DynamicPropertyValue VARCHAR(10)
);
INSERT @samplex
(
SiteID,
SubSiteID,
DynamicPropertyID,
DynamicPropertyName,
DynamicPropertyValue
)
VALUES
(1, 1, 1, 'Property1', 'ABC'),
(1, 1, 1, 'Property2', 'ABC'),
(1, 1, 1, 'Property3', 'ABC'),
(1, 1, 1, 'Property4', 'ABC'),
(2, 1, 2, 'Property5', 'ABC'),
(2, 1, 2, 'Property6', 'ABC'),
(2, 1, 2, 'Property1', 'ABC'),
(2, 1, 2, 'Property2', 'ABC'),
(3, 1, 2, 'Property3', 'ABC'),
(3, 1, 2, 'Property4', 'ABC'),
(3, 1, 3, 'Property5', 'ABC'),
(4, 1, 4, 'Property6', 'ABC');
SELECT *
FROM @samplex
PIVOT
(
MAX(DynamicPropertyValue)
FOR [DynamicPropertyName] IN ([Property1], [Property2], [Property3], [Property4], [Property5], [Property6])
) pvt;