我需要知道' pivot'如果没有要使用的聚合函数,则可以使用MS SQL将行转换为列。我看到很多只有聚合函数的例子。我的字段是字符串数据类型,我需要将此行数据转换为列数据。这就是我写这个问题的原因。我只是用' case'来做。任何人都可以帮助我......提前致谢。
答案 0 :(得分:14)
您可以使用PIVOT执行此操作。在执行PIVOT时,您可以使用以下两种方法之一:使用Static Pivot编写要转换的行,或使用Dynamic Pivot在运行时创建列列表:
Static Pivot(见SQL Fiddle with a Demo):
SELECT *
FROM
(
select empid, wagecode, amount
from t1
) x
pivot
(
sum(amount)
for wagecode in ([basic], [TA], [DA])
) p
Dynamic Pivot:
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)
这两个都会给你相同的结果
答案 1 :(得分:1)
样本格式
empid工资代码金额
1基本1000
1 TA 500
1 DA 500
2基本1500
2 TA 750
2 DA 750
empid basic 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
答案 2 :(得分:0)
试试这个:
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