透视具有多个值的表

Posted

技术标签:

【中文标题】透视具有多个值的表【英文标题】:Pivot a table with multiple values 【发布时间】:2018-12-07 18:01:28 【问题描述】:

我正在尝试旋转具有多个结果值的访问表,如下图中的第一个表。任何人都知道如何获得第二个表中的结果?

【问题讨论】:

【参考方案1】:

您不能将多个聚合与数据透视表一起使用,但有一个简单的解决方案可以解决您的问题

通过创建两个数据透视表并连接由价格和重量分隔的两个表是可能的。

/*PRICE*/

SELECT  MONTH
       ,ITEM
       ,STORE
       ,MANAGER
       ,[TY] AS TY_PRICE
       ,[LY] AS LY_PRICE
       ,[PY] AS PY_PRICE
INTO ##TMP_PRICE
FROM(
      select MONTH
            ,ITEM
            ,STORE
            ,MANAGER
            ,TYPE
            ,SUM(PRICE) AS PRICE
      FROM TABLE_X
      GROUP BY MONTH
            ,ITEM
            ,STORE
            ,MANAGER
            ,TYPE) AS TMP
PIVOT(
MAX(PRICE)
FOR TYPE IN([TY],[LY],[PY])
) AS PVT

/*WEIGHT*/

SELECT  MONTH
       ,ITEM
       ,STORE
       ,MANAGER
       ,[TY] AS TY_WEIGHT
       ,[LY] AS LY_WEIGHT
       ,[PY] AS PY_WEIGHT
INTO ##TMP_WEIGHT
FROM(
      select MONTH
            ,ITEM
            ,STORE
            ,MANAGER
            ,TYPE
            ,SUM(WEIGHT) AS WEIGHT
      FROM TABLE_X
      GROUP BY MONTH
            ,ITEM
            ,STORE
            ,MANAGER
            ,TYPE) AS TMP
PIVOT(
MAX(WEIGHT)
FOR TYPE IN([TY],[LY],[PY])
) AS PVT

创建两个表后加入它们

SELECT ISNULL(TP.month,TW.month)  as MONTH
      ,ISNULL(TP.ITEM,TW.ITEM) AS ITEM
      ,ISNULL(TP.STORE,TW.STORE) AS STORE
      ,ISNULL(TP.MANAGER,TW.MANAGER) AS MANAGER
      ,TY_WEIGHT
      ,LY_WEIGHT
      ,PY_WEIGHT
      ,TY_PRICE
      ,LY_PRICE
      ,PY_PRICE
FROM ##TMP_PRICE TP
FULL JOIN ##TMP_WEIGHT TW ON (TP.MONTH = TW.MONTH AND TP.ITEM = TW.ITEM 
                            AND TP.STORE = TW.ITEM AND TP.MANAGER = TW.MANAGER)

【讨论】:

这看起来像 Transact SQL,对吧?所以它在 Microsoft Access 中不起作用。【参考方案2】:

因为您不能将透视查询用作 Microsoft Access 查询中的子查询,所以您必须保存两个透视查询来分隔 Microsoft Access 查询对象:

Pivot_Price

TRANSFORM Sum([Price]) AS SumPrice
SELECT [month], item, store, manager
FROM Table1
GROUP BY [month], item, store, manager
PIVOT [type];

枢轴重量

TRANSFORM Sum([Weight]) AS SumWeight
SELECT [month], item, store, manager
FROM Table1
GROUP BY [month], item, store, manager
PIVOT [type];

然后将它们加入第三个查询:

SELECT
  PP.Month,
  PP.item,
  PP.store,
  PP.manager,
  PP.TY AS [TY-Price],
  PP.LY AS [LY-Price],
  PP.PY AS [PY-Price],
  PW.TY AS [TY-Weight],
  PW.LY AS [LY-Weight],
  PW.PY AS [PY-Weight]
FROM
  Pivot_Price AS PP INNER JOIN Pivot_Weight AS PW
ON
  PP.month = PW.month AND
  PP.item = PW.item AND
  PP.store = PW.store AND
  PP.manager = PW.manager

【讨论】:

非常感谢。泰语正是我所需要的!

以上是关于透视具有多个值的表的主要内容,如果未能解决你的问题,请参考以下文章

具有多个值列的数据透视表

Laravel 将枢轴附加到具有多个值的表

具有产品 ID 和该 ID 的多个值的表的 Sql 查询

透视具有一个标题行和一个数据行的表

使用 JavaScript,如何在具有多个值的日期列的表中突出显示“今天”的每个日期

按日期显示多个值的数据透视表