当列是字符串数据类型时,使用 mssql 中的“Pivot"将行转换为列字符串、转换为、数据类型、mssql

2023-09-08 09:51:20 作者:阑珊渔火

如果没有要使用的聚合函数,我需要知道是否可以使用 MS SQL 中的pivot"将行转换为列.我看到很多只有聚合函数的例子.我的字段是字符串数据类型,我需要将此行数据转换为列数据.这就是我写这个问题的原因.我只是用案例"来做的.任何人都可以帮助我......提前谢谢.

I need to know whether 'pivot' in MS SQL can be used for converting rows to columns if there is no aggregate function to be used. i saw lot of examples with aggregate function only. my fields are string data type and i need to convert this row data to column data.This is why i wrote this question.i just did it with 'case'. Can anyone help me......Thanks in advance.

推荐答案

你可以使用 PIVOT 来执行这个操作.执行 PIVOT 时,您可以通过以下两种方式之一进行操作,使用静态 Pivot,您将编码要转换的行,或者使用 Dynamic Pivot,它将在运行时创建列列表:

You can use a PIVOT to perform this operation. When doing the PIVOT you can do it one of two ways, with a Static Pivot that you will code the rows to transform or a Dynamic Pivot which will create the list of columns at run-time:

Static Pivot(参见 SQL Fiddle with a Demo):

Static Pivot (see SQL Fiddle with a Demo):

SELECT *
FROM
(
  select empid, wagecode, amount
  from t1
) x
pivot
(
  sum(amount)
  for wagecode in ([basic], [TA], [DA])
) p

动态枢轴:

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

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

set @query = 'SELECT empid, ' + @cols + ' from 
             (
                 select empid, wagecode, amount
                 from t1
            ) x
            pivot 
            (
                sum(amount)
                for wagecode in (' + @cols + ')
            ) p '

execute(@query)

这两个都会给你相同的结果

Both of these will give you the same results