我如何在这些数据上使用 PIVOT:?
I have a SQL Server table that looks like this:
RESOURCE | DESCRIPTION | VALUE
Test A Name | Resource A-xyz
Test A | Height | 20
Test A | Unit | ft
Test A | Location | Site 1
Test B | Volume | 30
Test C | Width | 10
Test C | Unit | in
I would like to get it into this format:
RESOURCE | Name | Height | Unit | Location | Volume | Width
Test A | Resource A-xyz | 20 | ft | Site 1 | |
Test B | | | | | 30 |
Test C | | | in | | | 10
One of the issues that I have is that there is no set pattern for description; for example, resource "Test B" might have all of the same descriptions as "Test A", while "Test C", might be missing some, and "Test D" might have a totally different set.
So far Google is suggesting that I want to use a pivot table, but I am still not sure how to do that with the above data.
解决方案In the end, I did the following:
- Selected all distinct descriptions (more than 70!).
- Created a table that had resource and every single distinct description as fields
- Populated resource column distinct resource names
- Ran a series of updates to populate remaining columns for each distinct resource name.
For example
CREATE TABLE #tb1
(
[RESOURCE] varchar(100),
[FIELD1] varchar(100),
[FIELD2] varchar(50),
.
.
.
[LAST FIELD] varchar(50),
)
INSERT INTO #tb1 (RESOURCE)
SELECT DISTINCT RESOURCE FROM tb2
ORDER BY Resource ASC
UPDATE #tb1 SET [FIELD1] = (SELECT VALUE FROM tb2 WHERE Resource = #tb1.Resource and Property = [FIELD1])
.
.
.
UPDATE #tb1 SET [LAST FIELD] = (SELECT VALUE FROM tb2 WHERE Resource = #tb1.Resource and Property = [LAST FIELD])
相关文章