高手请进!!连接查询疑难问题.
表A
time number duration
11:23 8610114 3
11:25 862153167855 10
12:13 8613511111111 3
11:55: 85299998888 7
... .....
表B
description country_code area_code price
中国北京 86 10 0.1
中国上海 86 21
中国其他 86 0.2
香港手机 852 9 1.5
香港其他 852 1
.... .... ... ....
根据表A中number 中的 country_cde 和are_code, 找到相应费率, 按description 分类统计出每个地区的总费用,
本人解决如下: select b.description ,sum(a.duraion*b.price) from A join B
on a.number like b.country_code+b.area_code+ '% '
但出现一个问题是 例如 数据8610114 在 '中国北京 '中被累加过,同时在 '中国其它 '中
又被加了一遍,因为它同时满足 '8610% ' 和 '86% ' 希望A中的数据,只根据B表统计一次,谢谢!
[解决办法]
修正和测试
declare @A table (
time varchar(20),
number varchar(30),
duration int
)
insert @A select
'11:23 ', '8610114 ' , 3
union all select
'11:25 ', '862153167855 ' , 10
union all select
'12:13 ', '8613511111111 ', 3
union all select
'11:55 ', '85299998888 ' , 7
declare @B table (
description Nvarchar(30),
country_code varchar(10),
area_code varchar(10),
price numeric(18,2)
)
insert @B select
N '中国北京 ', '86 ', '10 ', 0.1
union all select
N '中国上海 ', '86 ', '21 ',0.15
union all select
N '中国其他 ', '86 ', ' ' , 0.2
union all select
N '香港手机 ', '852 ', '9 ' , 1.5
union all select
N '香港其他 ', '852 ', ' ' , 1
select b.description ,sum(a.duration*b.price) from @A a join @B b
on a.number like b.country_code+b.area_code+ '% ' and not exists (
select 1 from @B b1 where len(b1.country_code+b1.area_code)> len(b.country_code+b.area_code) and a.number like b1.country_code+b1.area_code+ '% '
)
group by b.description
--结果
description
------------------------------ ---------------------------------------
香港手机 10.50
中国北京 0.30
中国其他 0.60
中国上海 1.50
(4 行受影响)
[解决办法]
--修改下Yang_(扬帆破浪)的,也可以用了
declare @A table (
time varchar(20),
number varchar(30),
duration int
)
insert @A select
'11:23 ', '8610114 ' , 3
union all select
'11:25 ', '862153167855 ' , 10
union all select
'12:13 ', '8613511111111 ', 3
union all select
'11:55 ', '85299998888 ' , 7
declare @B table (
description Nvarchar(30),
country_code varchar(10),
area_code varchar(10),
price numeric(18,2)
)
insert @B select
N '中国北京 ', '86 ', '10 ', 0.1
union all select
N '中国上海 ', '86 ', '21 ',0.15
union all select
N '中国 ', '86 ', Null , 0.2
union all select
N '香港手机 ', '852 ', '9 ' , 1.5
union all select
N '香港 ', '852 ', ' ' , 1
select b.description ,sum(a.duration*b.price) from @A a join @B b
on a.number like b.country_code+IsNull(b.area_code, ' ')+ '% ' and not exists (
select 1 from @B b1 where len(b1.country_code+IsNull(b1.area_code, ' '))> len(b.country_code+IsNull(b.area_code, ' ')) and a.number like b1.country_code+IsNull(b1.area_code, ' ')+ '% '
)
group by b.description
/*
中国.60
中国上海1.50
中国北京.30
香港手机10.50
*/