如何将行动态地转换为列SQL Server

时间:2016-05-19 09:10:52

标签: sql sql-server

我有一个请求返回这样的内容:

--------------------------
Tool     | Week | Value
--------------------------
Test     | 20   | 3
Sense    | 20   | 2
Test     | 19   | 2

我希望我的输入看起来像这样:

-------------------------
Tool     | W20  | W19
-------------------------
Test     | 3    | 2
Sense    | 2    | null

基本上,我需要每周都有一个新专栏。周数和工具是动态的。

我尝试过很多东西,但没有任何效果。有人有解决方案吗?

3 个答案:

答案 0 :(得分:1)

IF OBJECT_ID('tempdb..#temp') IS NOT NULL
    DROP TABLE #temp
    CREATE  TABLE #temp
        ( Tool  varchar(5),  Week  int,  Value  int)
    ;

    INSERT INTO #temp
        ( Tool ,  Week ,  Value )
    VALUES
        ('Test', 20, 3),
        ('Sense', 20, 2),
        ('Test', 19, 2)
    ;




    DECLARE @statement NVARCHAR(max)
    ,@columns NVARCHAR(max),
    @col NVARCHAR(max)


    SELECT @columns = ISNULL(@columns + ', ', '') + N'[' +'w'+ tbl.[Week] + ']'
    FROM (
       SELECT DISTINCT CAST([Week] AS VARCHAR)[Week]
       FROM #temp
       ) AS tbl

    SELECT @statement = 'SELECT *

    FROM
        (
        SELECT 
             Tool ,  ''w''+ CAST(Week AS VARCHAR) week ,  Value
         FROM 
             #Temp

            ) src   
    PIVOT(MAX(Value)for Week in  (' + @columns + ')) as pvt
    '

    EXEC sp_executesql @statement = @statement

答案 1 :(得分:1)

试试这个

CREATE table #tst (
Tool varchar(50), [Week] int, Value int
)

insert #tst 
values
('Test', 20, 3),
('Sense', 20,2),
('Test', 19, 2)

以下是动态查询:

DECLARE @col nvarchar(max), @query NVARCHAR(MAX)

SELECT @col = STUFF((SELECT DISTINCT ',' + QUOTENAME('W' + CAST([Week] as VARCHAR)) 
                from #tst
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

SET @query = '
SELECT *
    FROM   (
        SELECT Tool,
               Value,
               ''W'' + CAST([Week] as VARCHAR) AS WeekNo
        FROM   #tst
    ) t
    PIVOT
    (
        MAX(t.Value)
        FOR WeekNo IN (' + @col + ')
    ) pv
 ORDER by Tool'

 EXEC (@query)

<强>结果

Tool    W20  W19
=================
Sense   2    NULL
Test    3    2

答案 2 :(得分:0)

我就是这样做的......如果我理解你的问题

if object_id('tempdb..#InputTool') is not null drop table #InputTool
create table #InputTool (Tool nvarchar(10), [20] int, [19] int)

insert into #InputTool (Tool, [20], [19])
values 
('Test', 3, 2),
('Sense', 2, null)

declare @cols nvarchar(max)
select @cols = STUFF((SELECT ',' + QUOTENAME(name) 
                        from tempdb.sys.columns 
                        where object_id = object_id('tempdb..#InputTool') 
                        and Column_id > 1
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

declare @sqlquery nvarchar(max) =
'select Tool, Weeks, Value from (
    select * from #InputTool
    ) as it 
    UNPIVOT 
    (
    Value FOR Weeks IN (' + @cols + ')
    ) AS Weeks
order by Weeks desc'

execute (@sqlquery);

试一试,让我知道它是否有效