T-SQL:在没有连接的情况下在不同的表中查找行

时间:2012-02-07 08:47:52

标签: tsql

我有两个表,我将调用TableA和TableB

表A:

StartNumber EndNumber Country

1           10        USA
11          20        USA
21          30        Canada
31          40        France
41          50        France
51          60        Germany

表B:

SomeNumber
5
15
55
22
35
46
49

对于TableB中的每个数字,我想在TableA中找到相应的行,其中数字在StartNumber和EndNumber之间,并返回国家/地区的名称。然后,我想将这些结果分组到国家/地区列,并返回每个国家/地区显示的次数。所以结果看起来像这样:

Country Occurrences
USA     2
Germany 1
Canada  1
France  3

不知道该怎么做。

2 个答案:

答案 0 :(得分:2)

这里是查询。

Select A.Country, count(*) as Occurrences
from 
 tableA A
    inner join
 tableB B
    on B.someNumber between a.startnumber and b.endnumber
group by A.country

答案 1 :(得分:0)

这应该可以解决问题(但确实使用了连接):

declare @TableA table (StartNumber int, EndNumber int, Country varchar(16));
insert into @TableA (StartNumber, EndNumber, Country)
select 1, 10, 'USA' union
select 11, 20, 'USA' union
select 21, 30, 'Canada' union
select 31, 40, 'France' union
select 41, 50, 'France' union
select 51, 60, 'Germany';

declare @TableB table (SomeNumber int);
insert into @TableB (SomeNumber)
select 5 union
select 15 union
select 55 union
select 22 union
select 35 union
select 46 union
select 49;

select
    a.Country, count(*) Occurrences 
from
    @TableA a inner join
    @TableB b on b.SomeNumber between a.StartNumber and a.EndNumber
group by
    a.Country;