[英]SQL Pivot grand total row?
我有一個與用戶合作的數據透視圖,並且該用戶能夠查看其他帳戶。 下面是數據透視表的結果
Accounts | Toms
Bank 40
Bank2 50
它的關鍵代碼是...
SELECT * FROM
(SELECT
UserPivot.[parties]
,UserPivot.[Accounts]
,UserPivot.[CurrentAmount]
,UserPivot.[Plus / Negative]
FROM UserPivot) AS BaseData
PIVOT(
SUM(BaseData.[CurrentAmount])
FOR BaseData.[parties]
IN([Toms])
) AS PivotTable
有沒有一種方法可以計算出湯姆斯帳戶的總數?
謝謝大家的建議!
我將使用條件聚合,以便可以使用GROUPING SETS
:
SELECT UserPivot.Accounts,
SUM(CASE WHEN UserPivot.parties = 'Toms' THEN UserPivot.CurrentAmount
FROM UserPivot
GROUP BY GROUPING SETS ( ( UserPivot.Accounts), () );
老實說,我寧願為此使用一份報告。 但是,如果我被迫在查詢中執行此操作,則可以使用帶有條件和ROLLUP
運算符的標准聚合(用於小計和總計):
SELECT Accounts, [Plus / Negative], SUM(CurrentAmount) AS Toms
FROM UserPivot
WHERE parties = 'Toms'
GROUP BY [Accounts], [Plus / Negative] WITH ROLLUP;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.