行值到列

时间:2013-08-12 15:03:19

标签: sql ms-access ms-access-2007 pivot ms-access-2010

我有下表:

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中没有,这就是我正在使用的。

1 个答案:

答案 0 :(得分: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     |
+-------+--------+--------+--------+

编辑:表中的数据本身并不是有序的,但如果您有一个列按照您想要的顺序放置数据等,那么您应该能够将查询更改为以下内容:

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     |
+-------+--------+--------+--------+