假设您使用的是 SQL Server,您可以实现PIVOT函数将数据行转换为列。基本语法将是:
select *
from
(
select description, balance
from yourtable
) d
pivot
(
sum(balance)
for description in ([desc1], desc2]) -- replace this with the names of your descriptions
) piv;
当然,如果您有未知数量的描述值,那么您将需要使用动态 SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(description)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + '
from
(
select description, balance
from yourtable
) x
pivot
(
sum(balance)
for description in (' + @cols + ')
) p '
execute sp_executesql @query