来自枢轴的两列的总和

时间:2014-09-18 09:28:24

标签: sql sql-server

我有以下查询

SET @sql = N'
SELECT distinct ' + @columns2 + ', p1.*

   FROM  
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;

我期待从枢轴p和枢轴p2执行每列的总和([MontantAccoss])+ sum([MontantHorsAccoss])?任何的想法 ?非常感谢提前。

1 个答案:

答案 0 :(得分:0)

试试这个:

SET @sql = N'
SELECT distinct ' + @columns2 + ', p1.*, SUM(p.s, p1.s1)

   FROM  
INNER JOIN 
(SELECT 
  [CALF_AN]
      ,[CALF_NPERIODE]
      ,[CNT_ID]
      --,[PER_ID]
    ,[MontantAccoss]
    ,SUM(MontantAccoss) [s]
  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]
    , SUM(MontantHorsAccoss) [s1]
  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;