您可以通过同时应用UNPIVOT
和PIVOT
函数来获得所需的结果。如果您有已知数量的agent
要转换为列的值,则可以对查询进行硬编码:
select
case when TransactionType is null then 'Total' else [Credit/Debit] end [Credit/Debit],
case when TransactionType is null then '' else TransactionType end TransactionType,
Sum([Agent 1]) Agent1,
sum([Agent 2]) Agent2
from
(
select [Agent],
[Credit/Debit],
PaymentType as TransactionType,
value
from TableA
unpivot
(
value
for [Credit/Debit] in ([AmountCredit], [AmountDebit])
) unpiv
) src
pivot
(
sum(value)
for agent in ([Agent 1], [Agent 2])
) piv
group by GROUPING SETS ([Credit/Debit], TransactionType), ([Credit/Debit]);
请参阅SQL Fiddle with Demo。
如果您的数量未知,agents
那么您将需要使用动态 SQL,但不能在视图中使用动态 SQL,您必须将代码放在存储过程中。动态 SQL 将是:
DECLARE @cols AS NVARCHAR(MAX),
@colSum AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Agent)
from TableA
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colSum = STUFF((SELECT distinct ', Sum(' + QUOTENAME(Agent)+') as ' +QUOTENAME(Agent)
from TableA
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'select
case when TransactionType is null then ''Total'' else [Credit/Debit] end [Credit/Debit],
case when TransactionType is null then '''' else TransactionType end TransactionType,
'+@colSum +'
from
(
select [Agent],
[Credit/Debit],
PaymentType as TransactionType,
value
from TableA
unpivot
(
value
for [Credit/Debit] in ([AmountCredit], [AmountDebit])
) unpiv
) src
pivot
(
sum(value)
for agent in ('+@cols+')
) piv
group by GROUPING SETS ([Credit/Debit], TransactionType), ([Credit/Debit])'
execute(@query)
请参阅SQL Fiddle with Demo。查询的结果将是:
| CREDIT/DEBIT | TRANSACTIONTYPE | AGENT 1 | AGENT 2 |
------------------------------------------------------
| AmountCredit | Cash | 20 | 40 |
| AmountCredit | Credit Card | 20 | 20 |
| Total | | 40 | 60 |
| AmountDebit | Cash | 20 | 40 |
| AmountDebit | Credit Card | 10 | 10 |
| Total | | 30 | 50 |