您可以通過應用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,
'[email protected] +'
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 ('[email protected]+')
) 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 |
你可能想發佈的東西你已經嘗試過呢。 – 2013-03-04 14:04:52
如果代理人數量隨時間而變化,則無法將其作爲視圖編寫。 SQL不是電子表格系統。查詢產生的列數(及其類型和名稱)是固定的。 – 2013-03-04 14:05:44