【问题标题】:Need to create a SQL statement in MS Access (2010) to count multiple records in a range需要在 MS Access (2010) 中创建一条 SQL 语句来统计一个范围内的多条记录
【发布时间】:2018-12-06 11:55:51
【问题描述】:

我在 MS 访问中有两个表。需要创建一个表来查找 table1 中的范围并计算 table2 中该范围内的记录。

表1

FROM        TO
00100000    00799999
00800000    00899999
00900000    01599999
01600000    01899999

表2

Acct
00103614
00103615
00103624
00103626
00104001
00104002
00104003
00104004
00104302
00104400
00104401
00104404
00104406
00104407
01622345
01622347
01622353
01622357
01622359
01622362
01622365
01622366
01622368

期望的输出:

FROM        TO          Count
00100000    00799999    50
00800000    00899999    10
00900000    01599999     0
01600000    01899999    42

谢谢 弗兰克

【问题讨论】:

    标签: sql vba ms-access-2010


    【解决方案1】:

    使用相关子查询:

    select *, (select count(*) 
               from table2 t2 
               where t2.acct >= t1.from and 
                     t2.acct <= t1.to
              ) as Count
    from table1 t1;
    

    【讨论】:

      【解决方案2】:

      我会这样做:

      select count(*) as count, table1.tfrom, table1.to
      from table2, table1
      where table2.acct between table1.tfrom and table1.to
      group by table1.tfrom, table1.to;
      

      请避免在表/列名中使用“SQL”字样,例如 from 和 to

      【讨论】:

      • 我试过了,但在查询表达式 't1.acct between t1.from, t1.to' 中出现语法错误(逗号)
      • 修复:在between子句末尾添加分号和and
      猜你喜欢
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多