• MSSQL行转列


    --6:带条件查询的参数化动态PIVOT行转列
    DECLARE @sql_str NVARCHAR(MAX)
    DECLARE @sql_col NVARCHAR(MAX)
    DECLARE @sql_where NVARCHAR(MAX)
    DECLARE @tableName SYSNAME --行转列表
    DECLARE @groupColumn SYSNAME --分组字段
    DECLARE @row2column SYSNAME --行变列的字段
    DECLARE @row2columnValue SYSNAME --行变列值的字段
    SET @tableName = 'PURTD'
    SET @groupColumn = 'TD004'
    SET @row2column = 'TD012'
    SET @row2columnValue = 'TD008'
    SET @sql_where = 'WHERE TD012 < ''20161101'''
    
    --从行数据中获取可能存在的列
    SET @sql_str = N'
    SELECT @sql_col_out = ISNULL(@sql_col_out + '','','''') + QUOTENAME(['+@row2column+']) 
        FROM ['+@tableName+'] '+@sql_where+' GROUP BY ['+@row2column+']'
    --PRINT @sql_str
    EXEC sp_executesql @sql_str,N'@sql_col_out NVARCHAR(MAX) OUTPUT',@sql_col_out=@sql_col OUTPUT
    --PRINT @sql_col
    
    SET @sql_str = N'
    SELECT * FROM (
        SELECT ['+@groupColumn+'],['+@row2column+'],['+@row2columnValue+'] FROM ['+@tableName+']'+@sql_where+') p PIVOT 
        (SUM(['+@row2columnValue+']) FOR ['+@row2column+'] IN ( '+ @sql_col +') ) AS pvt 
    ORDER BY pvt.['+@groupColumn+']'
    --PRINT (@sql_str)
    EXEC (@sql_str)

    结果:

    中年大叔学Delphi
  • 相关阅读:
    stream流的统计demo
    ResourceBundle 读取文件demo
    spring boot 配置Filter过滤器的两种方式
    java工厂模式demo
    ThreadLocalDemo
    观察者模式Demo
    大数字的计算
    rabbitMQ消息丢失
    CF671E(线段树+单调栈)
    2020集训队作业板刷记录(三)
  • 原文地址:https://www.cnblogs.com/redhat588/p/14480234.html
Copyright © 2020-2023  润新知