我如何在这些数据上使用 PIVOT:?

How Do I Use PIVOT On This Data:?(我如何在这些数据上使用 PIVOT:?)
本文介绍了我如何在这些数据上使用 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:?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)