Sql Server 动态行转列

  1. 定义需要行转列的字段
  2. 构造动态的SQL查询语句
DECLARE @cols AS NVARCHAR(MAX), @@sqlStr AS NVARCHAR(MAX)
-- 定义需要作为列的字段 F_ItemName
SELECT @cols = STUFF((SELECT ',' + QUOTENAME(F_ItemName)
     FROM tableA
     FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

-- 构造动态 SQL 查询语句
SET @sqlStr
    = N'
      SELECT * FROM (
      SELECT DISTINCT top 100 percent 
		    a.F_CustomerName,
		    a.F_CreateDate,
		    a.F_OrderNo,
			b.F_ItemName,
		    b.F_EnterValue
       FROM TableA a INNER JOIN TableB b sample ON a.F_OrderNo= b.F_OrderNo
   ) AS dataInfo PIVOT(MAX(F_EnterValue) FOR F_ItemName IN (' + @cols
 + N') ) AS lastData
    '

-- 执行动态 SQL 查询语句
EXEC  @@sqlStr

Sql Server 动态行转列_第1张图片

你可能感兴趣的:(SQL,Server,sql,sqlserver,数据库)