简体   繁体   English

T-SQL 透视行到列

[英]T-SQL Pivot Row to Column

I am using SQL Server 2012 and have a table that has the following columns:我正在使用 SQL Server 2012 并且有一个包含以下列的表:

ID, Date, CustomFieldName, CustomFieldValue ID、日期、自定义字段名称、自定义字段值

The CustomFieldName column has 100 values (I know how stupid this sounds) but for the sake of simplicity lets say they are CustomField1, CustomField2, CustomField3 CustomFieldName 列有 100 个值(我知道这听起来多么愚蠢)但为了简单起见,我们可以说它们是 CustomField1、CustomField2、CustomField3

I would like to create a pivot where the out put looks like我想创建一个输出看起来像的支点

ID, Date, CustomField1, CustomField2, CustomField3 where the Max date of CustomFieldVaue's is aggregated. ID、日期、CustomField1、CustomField2、CustomField3,其中汇总了 CustomFieldVaue 的最大日期。

I have failed horribly in this, but have some progress (though my max isnt right and getting a lot of wrong data)我在这方面失败得很厉害,但是取得了一些进展(尽管我的最大值不正确并且得到了很多错误的数据)

Any help would be appreciated!任何帮助,将不胜感激!

SELECT [date],[id], [CustomField1], [CustomField2], [CustomField3]
from
(
  SELECT [date], [id], [CustomFieldValue], [CustomFieldName], 
    row_number() over(partition by [CustomFieldName] order by [CustomFieldValue]) rn
  from CustomTable
) as st
pivot
(
  max([CustomFieldValue])
  FOR [CustomFieldName] in ([CustomField1], CustomField2, [CustomField3])
) as pivottable
order by [id]

Hope I got it right, you want to pivot the rows (COlumnName1,2,...etc) as columns, so I've made a little script that's ready to run.希望我做对了,您想将行(COlumnName1,2,...等)作为列进行透视,所以我制作了一个可以运行的小脚本。

I recommend CTE's when it comes to pivoting, makes it easier, if you want to see the whole structure of the query just do a select @xSqlString我推荐 CTE 在涉及到透视时,使它更容易,如果您想查看查询的整个结构,只需执行select @xSqlString

set nocount on;

create table 
    #testTable 
        (
            ID                  int identity(1,1),
            [Date]              datetime default getdate(),
            CustomFieldName     nvarchar(50),
            CustomFieldValue    date
        );

declare
    @i int = 0,
    @xSqlStringPivot  nvarchar(max) = '',
    @xSqlString       nvarchar(max) = '';

while(@i<=100)
begin

set
    @xSqlStringPivot += concat('CustomFieldName',cast(@i as nvarchar(50)),char(13), case when @i<100 then ', ' else '' end);

insert into #testTable
    (
        CustomFieldName,
        CustomFieldValue
    )
values
    (
        concat('CustomFieldName', cast(@i as nvarchar(50))),
        dateAdd(day,-@i,getdate())
    );

set
    @i += 1;

end;


select * from
    #testTable


set
    @xSqlString = 
        (
            'with ctePiv as
            (
            select
                t.CustomFieldName,
                t.CustomFieldValue
            from
                #testTable t
            )
            select
                *
            from
                ctePiv
            pivot
            (
                max(customFieldValue) for customFieldName in
                    (
                    '+ @xSqlStringPivot +'          
                    )
            )p'
        );

exec sp_executeSQL @xSqlString


drop table #testTable;

Edit 1编辑 1

  1. I am referencing the custom table on the while block, basically I'm iterating 100 times to populate the table with 100 rows.我正在引用 while 块上的自定义表,基本上我要迭代 100 次以用 100 行填充表。 This is just to simulate your case.这只是为了模拟你的情况。

    while(@i<=100) begin while(@i<=100) 开始

    set @xSqlStringPivot += concat('CustomFieldName',cast(@i as nvarchar(50)),char(13), case when @i<100 then ', ' else '' end); set @xSqlStringPivot += concat('CustomFieldName',cast(@i as nvarchar(50)),char(13), case when @i<100 then ', ' else '' end);

    insert into #testTable ( CustomFieldName, CustomFieldValue ) values ( concat('CustomFieldName', cast(@i as nvarchar(50))), dateAdd(day,-@i,getdate()) );插入 #testTable ( CustomFieldName, CustomFieldValue ) 值 ( concat('CustomFieldName', cast(@i as nvarchar(50))), dateAdd(day,-@i,getdate()) );

    set @i += 1;设置@i += 1;

    end;结尾;

  2. @xSqlStringPivot is just a small trick to make a list of elements (CustomFieldName0, CustomFieldName1, etc) and to concatenate it to a dynamic SQL string, notice that I'm doing this in the while block, I just concatenate 'CustomField' with the current iteration number and with a carry feed (space). @xSqlStringPivot 只是制作元素列表(CustomFieldName0、CustomFieldName1 等)并将其连接到动态 SQL 字符串的一个小技巧,注意我在 while 块中执行此操作,我只是将“CustomField”与当前迭代次数和进位进位(空格)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM