访问SQL查询多记录到单记录

时间:2019-01-14 12:05:04

标签: sql ms-access

我有一个名为testdb的MS Access数据库,表名称为table1。

该表具有2个字段BinNo和Prodcode。

BinNo有很多重复的行,我想对BinNo进行分组,只要它有重复的行即可创建新的别名列(如单个记录)。

给出以下数据:

 +---------+----------+
 |  BinNo  | Prodcode |
 +---------+----------+
 | Bin no1 | Pro 1    |
 | Bin no1 | Pro 2    |
 | Bin no1 | Pro 3    |
 | Bin no2 | Pro 4    |
 | Bin no2 | Pro 5    |
 +---------+----------+

这是预期的结果:

 +---------+-----------+-----------+-----------+
 |  BinNo  | Prodcode1 | Prodcode2 | Prodcode3 |
 +---------+-----------+-----------+-----------+
 | Bin no1 | Pro 1     | Pro 2     | Pro 3     |
 | Bin no2 | Pro 4     | Pro 5     |           |
 +---------+-----------+-----------+-----------+

1 个答案:

答案 0 :(得分:2)

这回答了问题的原始版本。

这在MS Access中确实很痛苦。您可以使用条件聚合来做到这一点。这是一种方法:

error: ref updates forbidden inside quarantine environment

子查询本质上实现了select t1.binno, max(iif(seqnum = 1, prodcode, null)) as prodcode_1, max(iif(seqnum = 2, prodcode, null)) as prodcode_2, max(iif(seqnum = 3, prodcode, null)) as prodcode_3 from (select t1.*, (select count(*) from table1 as tt1 where tt1.binno = t1.binno and tt1.prodcode <= t1.prodcode ) as seqnum from table1 as t1 ) as t1 group by t1.binno; ,在MS Access中不可用。