How Do I Use PIVOT On This Data:?

前端 未结 4 1273
抹茶落季
抹茶落季 2021-01-16 16:24

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          


        
4条回答
  •  鱼传尺愫
    2021-01-16 16:42

    In the end, I did the following:

    1. Selected all distinct descriptions (more than 70!).
    2. Created a table that had resource and every single distinct description as fields
    3. Populated resource column distinct resource names
    4. 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])
    

提交回复
热议问题