MS Access通过PIVOT TRANSFORM旋转查询

时间:2015-11-19 12:00:47

标签: sql ms-access ms-access-2013

我在MS Access 2013中开发了一个数据库。 我需要从两个表中生成一个报告:inventory_type,inventory(以及一些T-SQL的经验)

库存表:

id
inv_type(FK of inventory_type.id)
inv_name, etc.

inventory_type表:

id
type_name

我使用GROUP BY进行简单查询:

SELECT it.type_name AS [Inventory name], Count(i.ID) AS Quantity
FROM inventory_type AS it INNER JOIN inventory AS i ON it.ID = i.inv_type
GROUP BY it.type_name;

此查询的结果是:

Inventory Name | Quantity
VideoCamera         3
PC                  5
.....

但结果应该是这样的:

Quantity | VideoCamera | PC
Quantity |     3          5

我试图这样做:

TRANSFORM Count(it.ID) AS Quantity
SELECT "Quantity"
FROM inventory_type AS it INNER JOIN inventory AS i ON it.ID = i.inv_type
GROUP BY it.type_name
PIVOT it.type_name;

但结果并不是我的预期:

Quantity | VideoCamera  |  PC
Quantity        3              
Quantity                    5

有人可以帮我解决这个问题,无法理解ms访问语义。

1 个答案:

答案 0 :(得分:0)

只需从type_name子句中删除GROUP BY

TRANSFORM Count(it.ID) AS CountOfQuantity 
SELECT 'Quantity' AS Quantity
FROM inventory_type AS it INNER JOIN inventory AS i ON it.ID = i.inv_type 
GROUP BY 'Quantity' 
PIVOT it.type_name;