-1

我有下表:

Name        Group
John        2A
John        1B
Barry       2A
Ron         1B
Ron         2A
Ron         2C

我正在尝试创建一个查询以将组列分隔为每个实例的新列。

预期结果

Name        Group1      Group2      Group3
John        2A          1B
Barry       2A
Ron         1B          2A          2C

在这个例子中,我知道最大组数是 3。所以我创建了 Group1、Group2 和 Group3 列。

有点像交叉表,但我不能使用交叉表,因为值选项需要是数字并且我有字符串。至少在我正在使用的 MS-Access 中没有。

4

1 回答 1

4

不幸的是,MS Access 没有一个row_number()功能可以轻松地为每个name. 我会通过以下方式得到结果。

首先,通过使用下面的查询,您将返回namegroup以及为每个人分配的每个组的递增数字:

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     |
+-------+--------+--------+--------+
于 2013-08-12T16:11:44.383 回答