多行转置为多列的一行。

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

我有一个MS Access项目,我想从一个表格中制作一个报表。我不太确定这是否可以做到。

以下是源表

Name    Fruits     Count
Jorge   Apple       4
Jorge   Mango       3
Jorge   Pears       4
Jorge   Pineapple   6
James   Apple       8
James   Mango       1
James   Pears       4
James   Pineapple   6

我想得到这样一个连续的结果。

Name    Apple   Mango   Pears   Pineapple
Jorge     4       3      4         6
James     8       1      4         6

有什么方法可以让一个SQL做到这一点?

sql ms-access access-vba
2个回答
3
投票

试试这个。

TRANSFORM sum(MyTable.count) AS noOfCount
SELECT MyTable.name
FROM MyTable
GROUP BY MyTable.name
PIVOT MyTable.fruits;

0
投票

你可以用条件聚合法 在MS Access中,这看起来像。

select name,
       sum(iif(fruit = "Apple", 1, 0)) as apple,
       sum(iif(fruit = "Mango", 1, 0)) as mango,
       sum(iif(fruit = "Pear", 1, 0)) as pear,
       sum(iif(fruit = "Pineapple", 1, 0)) as pineapple
from t
group by name,
© www.soinside.com 2019 - 2024. All rights reserved.