[英]Horizontal Grand Total in Pivot Table SQL
我有這個查詢工作:
select cap_idPlanoContasFin , [3684],[2234],[2] ,
from
(
select cap_idPlanoContasFin,cap_idempresa,sum(cap_valorfatura)
as Stotal
from erp_ContasPagar
group by cap_idPlanoContasFin , cap_idEmpresa
) as sourcetable
pivot
(sum(Stotal)for cap_idEmpresa in ([3684],[2234],[2])
)as pivottable;
此查詢返回:
cap_idPlanoContasFin 3684 2234 2
3 9000 NULL NULL
10 1057840,68 NULL 1865081,35
11 NULL 7283,1 591,9
12 NULL NULL 178914,45
13 9305,07 1117,6 500
14 NULL 59333,5 34611,74
我想在水平總示例中輸入相同的查詢:
cap_idPlanoContasFin 3684 2234 2 Total
---------------------------------------------------------------------
13 9305,07 1117,6 500 10922,67
怎么做到這個? 我用UNION
讀過一些東西。
首先,您不需要事先對數據進行分組:PIVOT子句將為您執行此操作。 因此,您可以刪除GROUP BY子句並相應地更改PIVOT中的SUM()
參數:
select cap_idPlanoContasFin, [3684], [2234], [2]
from
(
select cap_idPlanoContasFin, cap_idempresa, cap_valorfatura
from erp_ContasPagar
group by cap_idPlanoContasFin , cap_idEmpresa
) as sourcetable
pivot
(
sum(cap_valorfatura) for cap_idEmpresa in ([3684], [2234], [2])
) as pivottable;
要添加總列,可以使用如下窗口 SUM()
:
select cap_idPlanoContasFin, [3684], [2234], [2], Total
from
(
select cap_idPlanoContasFin, cap_idempresa, cap_valorfatura, sum(cap_valorfatura) over (partition by cap_idPlanoContasFin) as Total
from erp_ContasPagar
) as sourcetable
pivot
(
sum(cap_valorfatura) for cap_idEmpresa in ([3684], [2234], [2])
) as pivottable;
但請注意,如果您的sourcetable
包含的cap_idEmpresa
值不是PIVOT子句中列出的值,則相應的cap_valorfatura
值也會相加。 因此,您可能希望在sourcetable
之前過濾源表行集,如下所示:
select cap_idPlanoContasFin, [3684], [2234], [2], Total
from
(
select cap_idPlanoContasFin, cap_idempresa, cap_valorfatura,
sum(cap_valorfatura) over (partition by cap_idPlanoContasFin) as Total
from erp_ContasPagar
where cap_idempresa in (3684, 2234, 2)
) as sourcetable
pivot
(
sum(cap_valorfatura) for cap_idEmpresa in ([3684], [2234], [2])
) as pivottable;
謝謝大家,這是最后的查詢:
select cap_idPlanoContasFin, plc_classificador, plc_nomeConta,[3684], [2234], [2],
isnull ([2234],0) + isnull ([2],0) AS Subtotal ,Total
from
(
select A.cap_idempresa, A.cap_idPlanoContasFin, A.cap_valorfatura,
B.plc_classificador , B.plc_nomeConta,
sum(A.cap_valorfatura) over (partition by A.cap_idPlanoContasFin) as Total
from erp_ContasPagar A /*where cap_idempresa in (3684, 2234, 2)*/
inner join tbl_PlanoFinanceiro B on A.cap_idPlanoContasFin = B.plc_id
) as sourcetable
pivot
(
sum(cap_valorfatura) for cap_idEmpresa in ([3684], [2234], [2])
) as pivottable;
我需要使用isnull來將NULL更改為su到sume小計。 再次感謝您的幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.