简体   繁体   中英

Need to create a SQL statement in MS Access (2010) to count multiple records in a range

I have two tables in MS access. Need to create a table that lookups the ranges in table1 and counts the records in table2, within that range.

Table1

FROM        TO
00100000    00799999
00800000    00899999
00900000    01599999
01600000    01899999

Table2

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

Desired output:

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

Thanks Frank

I'll do something like this:

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;

please avoid "SQL" words like from and to in table/column names

Use correlated subquery :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM