SQL Server 中的动态枢轴列

Dynamic Pivot Columns in SQL Server(SQL Server 中的动态枢轴列)
本文介绍了SQL Server 中的动态枢轴列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我在 SQL Server 中有一个名为 Property 的表,其中包含以下列:


I have a table named Property with following columns in SQL Server:

Id    Name

这个表中有一些属性,其他表中的某个对象应该赋予它价值.

there are some property in this table that certain object in other table should give value to it.

Id    Object_Id    Property_Id    Value

我想制作一个如下所示的数据透视表,其中我在第一个表中声明的每个属性都有一列:

I want to make a pivot table like below that has one column for each property I've declared in 1'st table:

Object_Id    Property1    Property2    Property3    ...

我想知道如何从表中动态获取数据透视列.因为第一个表中的行会改变.

I want to know how can I get columns of pivot dynamically from table. Because the rows in 1'st table will change.

推荐答案

是这样的:

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' +
                        QUOTENAME(Name)
                      FROM property
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)') 
                        , 1, 1, '');

SELECT @query =

'SELECT *
FROM
(
  SELECT
    o.object_id,
    p.Name,
    o.value
  FROM propertyObjects AS o
  INNER JOIN property AS p ON o.Property_Id = p.Id
) AS t
PIVOT 
(
  MAX(value) 
  FOR Name IN( ' + @cols + ' )' +
' ) AS p ; ';

 execute(@query);

SQL Fiddle 演示.

这会给你这样的东西:

SQL Fiddle Demo.

This will give you something like this:

| OBJECT_ID | PROPERTY1 | PROPERTY2 | PROPERTY3 | PROPERTY4 |
-------------------------------------------------------------
|         1 |        ee |        fd |       fdf |      ewre |
|         2 |       dsd |       sss |      dfew |       dff |

这篇关于SQL Server 中的动态枢轴列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

相关文档推荐

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代码排序)