我需要知道在MS SQL“支点”是否可用于行转换为列,如果有使用没有聚合函数。 我看到很多的只有聚合函数的例子。 我的字段是字符串数据类型,我需要这个行数据转换成列data.This就是为什么我写这question.i只是“案例”做到了。 谁能帮我......先谢谢了。
Answer 1:
您可以使用PIVOT执行此操作。 当进行PIVOT你能做到的两种方式,用静态枢轴,你将代码的行变换或动态透视,这将创造在运行时列的列表中选择一个:
静态枢轴(参见SQL拨弄演示 ):
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)
这两种会给你同样的结果
Answer 2:
样本格式
EMPID wagecode量
1基本1000
1 TA 500
1 DA 500
2基本1500
2 TA 750
2 DA 750
EMPID基本TA DA
1 1000 500 500
2 1500 750 750
我得到的答案是
SELECT empID , [1bas] as basic, [1tasal] as TA,[1otsal] as DA FROM ( SELECT empID, wage, amount FROM table) up PIVOT (SUM(amt) FOR wgcod IN ([1bas], [1tasal],[1otsal])) AS pvt ORDER BY empID GO
Answer 3:
试试这个:
SELECT empid AS EmpID
, ISNULL(SUM(CASE wagecode WHEN 'basic' THEN Amount ELSE 0 END), 0) AS Basic
, ISNULL(SUM(CASE wagecode WHEN 'ta' THEN Amount ELSE 0 END), 0) AS TA
, ISNULL(SUM(CASE wagecode WHEN 'da' THEN Amount ELSE 0 END), 0) AS DA
FROM Employee
GROUP BY empid
文章来源: Convert Rows to columns using 'Pivot' in mssql when columns are string data type