msaccess上的每月清单

时间:2019-01-23 15:00:59

标签: sql ms-access

我有一个下表所示的表格。我的目的是创建每月检查清单。

+-------------+----------------+-----------------+-----------------+
| id          | mem_id         | month_code      | type            |
+-------------+----------------+-----------------+-----------------+
|      1      |  1             |     Jan         |    to           |   
|      2      |  2             |     Feb         |    t            |   
|      3      |  1             |     Feb         |    to           |
|      4      |  3             |     Jan         |    o            |
|      5      |  1             |     Mar         |    o            |   
+-------------+----------------+-----------------+-----------------+

使用的查询是

SELECT distinct(mem_id) as Member,
(SELECT type FROM test where mem_id=Member and month_code='Jan') as Jan,
(SELECT type FROM test where mem_id=Member and month_code='Feb') as Feb,
(SELECT type FROM test where mem_id=Member and month_code='Mar') as Mar
FROM  test

所需的输出是

+-------------+----------------+-----------------+-----------------+
| mem_id      | Jan            | Feb             | Mar             |
+-------------+----------------+-----------------+-----------------+
|      1      |  to            |     to          |    o            |   
|      2      |                |     t           |                 |   
|      3      |  o             |                 |                 |   
+-------------+----------------+-----------------+-----------------+

但是,我的问题是代码在mysql上运行良好,但是在msaccess上弹出了一个输入框,要求我输入参数Member的值。如何在Access中获得正确的输出?

1 个答案:

答案 0 :(得分:0)

您可以改为进行条件聚合:

select mem_id,
       max(iif(month_code = 'Jan', type)) as Jan,
       max(iif(month_code = 'Feb', type)) as Feb,
       max(iif(month_code = 'Mar', type)) as Mar
from test t
group by mem_id;

对于您的查询,Member表中不存在名称test,因此access将该名称视为parameter

因此,您可能需要mem_id来代替:

SELECT t.mem_id as Member,
      (SELECT t1.type FROM test as t1 where t1.mem_id = t.mem_id and t1.month_code='Jan') as Jan,
      (SELECT t1.type FROM test as t1 where t1.mem_id = t.mem_id and t1.month_code='Feb') as Feb,
      (SELECT t1.type FROM test as t1 where t1.mem_id = t.mem_id and t1.month_code='Mar') as Mar
FROM test as t
GROUP BY t.mem_id;

唯一的问题是,对于您的版本,如果一个mem_id具有相同的type重复的month_code,那么它将引发subquery错误。

因此,您需要top中的subquery子句。