您的位置:首页 > 数据库

SQL解惑-谜题32计算税收

2017-08-10 22:20 120 查看

以删除行的思维理解嵌套语句的where A.b = B.b

题目不再赘述,数据库如下:

taxauthorities表



taxrates表



题目:求1994年11月1日city2的总税率是多少,单条语句SQL语句回答

答案1:



首先看两条select语句:

1.
select * from taxauthorities as t1,taxrates as t2 where t1.tax_authority = t2.tax_authority and t1.tax_area = 'city2';


得到结果:表1



2.
select * from taxrates where effect_date<'1994-11-01';


得到结果:表2



最后一个where条件的理解

and t2.effect_date =( select max(effect_date) from taxrates where tax_authority = t2.tax_authority and effect_date<=’1994-11-01’);

t2.effect_date = :在表1中把effect_date不满足条件的行删除掉

tax_authority = t2.tax_authority : 对于表1里每一个出现的tax_authority,代入到子查询,在表2中删除不相关的行(where tax_authority = t2.tax_authority),再选出最大的effect_date( select max(effect_date) )

比如说,对于表1中tax_authority=city2的行,代入子查询得到

select max(effect_date) from taxrates where tax_authority = 'city2' and effect_date<='1994-11-01'


where tax_authority = ‘city2’ 即在表2中删除掉tax_authority不等于city2的行

得到



select max(effect_date)得到 1994-01-01,返回给上一级查询

当t2.tax_authority = ‘city2’时,

select * from taxauthorities as t1,taxrates as t2 where t1.tax_authority = t2.tax_authority and t1.tax_area = ‘city2’ and t2.effect_date=’1994-01-01’



只有中间的行符合条件



类似地过程可以筛选出tax_authority=’county1’时表1的行和tax_authority=’state1’时表1的行





最后select sum(t2.tax_rate) 即2.0+2.5+1.1 = 5.6
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息