Hello ,
Please can anyone help me I wanna do the sum of two pivots results.
I do the pivot and the sum for the first row TEMPAccoss then I do the same thing for the second row TEMPHorsAccoss.
The problem is that after that I want to have the sum of the two results .How can I do that ?
This is my query :
DECLARE @columns NVARCHAR(MAX),@columns1 NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = '1,2,3,4';
SELECT @columns1 =
STUFF((
SELECT ',' + QUOTENAME(Value)
FROM dbo.SplitString(@columns,',')
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SET @sql = N'
SELECT distinct p.*,p1.*
FROM
SCHHAYS.dbo.WTEFAC EF
INNER JOIN SCHHAYS.dbo.WTFAC F ON EF.EFAC_NUM = F.EFAC_NUM
INNER JOIN SCHHAYS.dbo.WTFACINFO BS ON F.FAC_NUM = BS.FAC_NUM
INNER JOIN SCHHAYS.dbo.WTLFAC LF ON F.FAC_NUM = LF.FAC_NUM
INNER JOIN SCHHAYS.dbo.WTRUBVARIANTEFAC WRU ON LF.RINT_ID = WRU.RINT_ID
INNER JOIN SCHHAYS.dbo.WTACUMFAC WTA ON WRU.RUV_ID = WTA.RUV_ID
INNER JOIN SCHHAYS.dbo.WTCUMFAC WTA1 ON WTA.CUM_ID = WTA1.CUM_ID
INNER JOIN SCHHAYS.dbo.WTVTAT TAT ON BS.TIE_ID = TAT.TIE_ID AND BS.RFAN_ID = TAT.RFAN_ID AND BS.PER_ID = TAT.PER_ID AND BS.CNT_ID = TAT.CNT_ID
INNER JOIN SCHHAYS.dbo.WTTIEINT INT ON (TAT.TIE_ID = INT.TIE_ID) AND (TAT.VTAT_IORDRE = INT.TIEI_ORDRE)
INNER JOIN SCHHAYS.dbo.PYCONTRAT CC ON TAT.PER_ID = CC.PER_ID AND TAT.CNT_ID = CC.CNT_ID
INNER JOIN SCHHAYS.dbo.CMTIERS T ON TAT.TIE_ID = T.TIE_ID
INNER JOIN SCHHAYS.dbo.WTMISS M ON CC.PER_ID = M.PER_ID AND CC.CNT_ID = M.CNT_ID
INNER JOIN SCHHAYS.dbo.WTCNTI COT1 ON M.PER_ID = COT1.PER_ID AND M.CNT_ID = COT1.CNT_ID
INNER JOIN
(SELECT
[CALF_AN]
,[CALF_NPERIODE]
,[CNT_ID]
--,[PER_ID]
,[MontantAccoss]
from [Reporting].[dbo].[TEMPAccoss]
WHERE [CALF_AN]=2014
) AS j
PIVOT
(
sum([MontantAccoss])
for [CALF_NPERIODE] in ('+@columns1+')
) AS p ON p.CNT_ID = COT1.CNT_ID
INNER JOIN
(SELECT
[CALF_AN]
,[CALF_NPERIODE]
,[CNT_ID]
--,[PER_ID]
,[MontantHorsAccoss]
from [Reporting].[dbo].[TEMPHorsAccoss]
WHERE [CALF_AN]=2014
) AS j
PIVOT
(
sum([MontantHorsAccoss])
for [CALF_NPERIODE] in ('+@columns1+')
) AS p1 ON p1.CNT_ID = COT1.CNT_ID;';
PRINT @sql;
EXEC sp_executesql @sql;
Thanks in advance
ghada