将表中的日期转换为 MS Access 查询中的列

问题描述

我有一张如下表:

type_id 日期 顺序
20 2021-06-23 123
20 2021-06-23 217
35 2021-06-23 121
35 2021-06-24 128
20 2021-06-24 55
35 2021-06-25 77
20 2021-06-26 72
20 2021-06-26 71

并且只想在 type_id=20 的地方创建查询

2021-06-23 2021-06-24 2021-06-25 2021-06-25
123 55 72
217 71
  • 是否可以在没有 vba 的情况下使用 sql 执行此操作?
  • 如果需要 vba,我是否需要创建一个额外的表并且每次添加/删除一个新列?

如果有任何想法,请向您询问

解决方法

您可以使用条件聚合。但这在 MS Access 中很痛苦,因为您需要一个顺序值。你可以计算一个:

select max(iif(date = "2021-06-23",order,null)) as val_2021_06_23,max(iif(date = "2021-06-24",null)) as val_2021_06_24,max(iif(date = "2021-06-25",null)) as val_2021_06_25,max(iif(date = "2021-06-26",null)) as val_2021_06_26       
from (select t.*,(select count(*)
              from t as t2
              where t2.type_id = t.type_id and t2.date = t.date and t2.order <= t.order
             ) as seqnum
      from t
      where type_id = 20
     ) t
group by seqnum;
,

谢谢,成功了! (只需更改代码“2021-06-23”----> #2021-06-23#

与此同时,我找到了另一个解决方案,但这需要在表中添加一个新字段。该字段是一个数字字段,其中包含每天从 1 到 n 的序列号。在我的项目中它甚至很有帮助,因为在这种情况下我可以按列控制顺序

这是代码。也许对未来的某人有帮助

TRANSFORM
First ([tabela1].[order])
SELECT  [tabela1].[sequence]
FROM  [tabela1]
WHERE [tabela1].[type_id] = 20
GROUP BY [tabela1].[sequence]
PIVOT  [tabela1].[date]