不幸的是,MS Access 没有一个row_number()
功能可以轻松地为每个name
. 我会通过以下方式得到结果。
首先,通过使用下面的查询,您将返回name
,group
以及为每个人分配的每个组的递增数字:
select name,
group,
(select count(*)
from yourtable t1
where yourtable.name = t1.name
and yourtable.group<= t1.group) AS rw
from yourtable;
此查询将给出类似于以下内容的结果:
+-------+-------+----+
| name | group | rw |
+-------+-------+----+
| John | 2A | 1 |
| John | 1B | 2 |
| Barry | 2A | 1 |
| Ron | 1B | 3 |
| Ron | 2A | 2 |
| Ron | 2C | 1 |
+-------+-------+----+
然后您可以使用该IIF()
函数和max()
聚合函数将值从行转换为列:
SELECT name,
max(iif(rw=1, group, null)) as Group1,
max(iif(rw=2, group, null)) as Group2,
max(iif(rw=3, group, null)) as Group3
FROM
(
select name,
group,
(select count(*)
from yourtable t1
where yourtable.name = t1.name
and yourtable.group<= t1.group) AS rw
from yourtable
) d
group by name
order by name;
这将给出一个结果:
+-------+--------+--------+--------+
| name | Group1 | Group2 | Group3 |
+-------+--------+--------+--------+
| Barry | 2A | | |
| John | 2A | 1B | |
| Ron | 2C | 2A | 1B |
+-------+--------+--------+--------+
编辑:表中的数据不是天生有序的,但是如果您有一列可以使用 id 等按您想要的顺序放置数据,那么您应该能够将查询更改为以下内容:
SELECT name,
max(iif(rw=1, group, null)) AS Group1,
max(iif(rw=2, group, null)) AS Group2,
max(iif(rw=3, group, null)) AS Group3
FROM
(
SELECT name,
group,
(select count(*)
from table9 t1
where yourtable.name = t1.name
and t1.id<= yourtable.id
) as rw
from yourtable
) AS d
GROUP BY name
ORDER BY name;
结果将是:
+-------+--------+--------+--------+
| name | Group1 | Group2 | Group3 |
+-------+--------+--------+--------+
| Barry | 2A | | |
| John | 2A | 1B | |
| Ron | 1B | 2A | 2C |
+-------+--------+--------+--------+