数据透视表在SQL Server中缺少总计数据

时间:2019-04-10 10:41:40

标签: sql-server pivot-table

我有以下参考表:

$scope.formName = {};

然后我要按ProductType旋转表格:

CompanyId  ProductType ProductCount ProductBought
3          1            12          12
3          2            5           5
3          4            5           5

这将产生以下结果:

SELECT 
CompanyId, 
SUM(ProductBought) AS ProductBought
SUM(ISNULL([1], 0)) AS [1], 
SUM(ISNULL([2], 0)) AS [2], 
SUM(ISNULL([3], 0)) AS [3], 
SUM(ISNULL([4], 0)) AS [4]
FROM (
    SELECT * FROM @ReferenceTable
) AS a
PIVOT (
    SUM([ProductCount]) FOR ProductType IN ([1], [2], [3], [4])
) as pvt
GROUP BY pvt.CompanyId

我希望ProductBought的值为22,因此在透视图中,有5个会丢失。

如何通过数据透视表实现ProductBought的全部计数?

3 个答案:

答案 0 :(得分:2)

在您的查询中,金额根据ProductBrought列进行分组。因为对于两个ProductType 2,4 ProductBrought值都是5。数据分组为一个5。只需使用简单的行ID列将它们分开,然后尝试。

SELECT * INTO #TEMP FROM 
(
SELECT 3 companyId, 1 ProductType,12 ProductCount,12 ProductBought
UNION ALL
SELECT 3, 2,5 ,5  UNION ALL
SELECT 3, 4,5 ,5  
)
AS A 

查询

SELECT SUM(ProductBought)ProductBought,SUM([1]) [1],SUM([2])[2],SUM([3])[3],SUM([4])[4]
FROM (
SELECT ROW_NUMBER()OVER(PARTITION BY companyId ORDER BY (SELECT 1 )DESC)RN,* FROM #TEMP 
) AS A 
PIVOT ( SUM( ProductCOUNT ) FOR ProductType IN([1],[2],[3],[4])
)AS B
GROUP BY COMPANYID

答案 1 :(得分:1)

尝试一下

;WITH CTE(CompanyId,  ProductType, ProductCount, ProductBought)
AS
(
SELECT 3, 1,12,12 UNION ALL
SELECT 3, 2,5 ,5  UNION ALL
SELECT 3, 4,5 ,5  
)
SELECT  CompanyId, 
        ProductBought,
        ISNULL(SUM([1]),0) AS [1],
        ISNULL(SUM([2]),0) AS [2],
        ISNULL(SUM([3]),0) AS [3],
        ISNULL(SUM([4]),0) AS [4]
FROM
(
SELECT CompanyId,  
       ProductType, 
       ProductCount, 
       SUM(ProductBought)OVER(ORDER BY CompanyId) AS ProductBought 
FROM CTE
)AS SRC
PIVOT
(
SUM(ProductCount) FOR ProductType IN ([1],[2],[3],[4])
)
AS PVT
GROUP BY CompanyId,
         ProductBought

结果

CompanyId   ProductBought    1   2   3      4
------------------------------------------------
3             22            12   5    0      5

答案 2 :(得分:0)

您可以单独汇总并与以下枢轴结果合并。

SELECT MainTable.CompanyId, MainTable.ProductBought, PivotTable.[1], PivotTable.[2], 
PivotTable.[3], PivotTable.[4]
FROM
(
   SELECT ReferenceTable.CompanyId, SUM(ProductBought) AS ProductBought FROM 
   ReferenceTable
   GROUP BY CompanyId
) MainTable
INNER JOIN  
(
   SELECT 
     CompanyId, 
     SUM(ISNULL([1], 0)) AS [1], 
     SUM(ISNULL([2], 0)) AS [2], 
     SUM(ISNULL([3], 0)) AS [3], 
     SUM(ISNULL([4], 0)) AS [4]
     FROM (
       SELECT * FROM dbo.ReferenceTable
      ) AS a
     PIVOT (
       SUM([ProductCount]) FOR ProductType IN ([1], [2], [3], [4])
      ) as pvt
    GROUP BY pvt.CompanyId
) PivotTable 
ON PivotTable.CompanyId = MainTable.CompanyId