tsql - 需要帮助从具有动态属性的表创建透视视图
问题描述
我有一个大约 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 |
+--------+-----------+-----------+-----------+-----------+-----------------+-----------------+-----------------+
我面临的问题是,我们可能会随着时间的推移向表中添加新的“动态属性”,因此如果我们添加到每个 SiteID/SubsiteID 组合,视图需要能够动态更改以添加新列Property4
,例如.
非常感谢任何建议或帮助。
解决方案
试试下面的查询:
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;
推荐阅读
- java - 如何在 JSON 中为 Java 中的每个类字段创建对象列表
- c++ - 什么在这里定义为 const(char** 和 ie.)?
- efl - EFL - 窗口层次结构
- node.js - Dialogflow 中的 getArgument()
- python - 查看调用端点?
- java - maven-jaxb2-plugin 两个具有相同元素的 xsd
- android - 焦点外的 TextinputEdittext 和 TextInputLayout 应将提示返回到第一个状态
- jquery - 获取检查了多少复选框和单选按钮
- r - 计算数据框列中的唯一元素
- python - 散景“显示”给出 AttributeError:“NoneType”对象没有属性“引用”