我如何在这些数据上使用 PIVOT:? [英] How Do I Use PIVOT On This Data:?

查看:18
本文介绍了我如何在这些数据上使用 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:

  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])

这篇关于我如何在这些数据上使用 PIVOT:?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆