数据透视表在SQL Server中总和丢失数据

问题描述 投票:0回答:3

我有以下参考表:

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

然后我按ProductType转动表格:

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

这给出了以下结果:

CompanyId  ProductBought   1   2   3   4
3          17              12  5   0   5

我希望ProductBought值为22,所以在数据透视中,有5个缺失。

如何使用数据透视表实现ProductBought的完整计数?

sql-server pivot-table
3个回答
2
投票

在您的查询中,数量基于ProductBrought列进行分组。因为两个ProductType 2,4 ProductBrought值都是5。数据分组在一个单独的5上。只需使用简单的Row 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
投票

试试这个

;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

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
© www.soinside.com 2019 - 2024. All rights reserved.