1. 程式人生 > >SQL解惑-謎題32計算稅收

SQL解惑-謎題32計算稅收

以刪除行的思維理解巢狀語句的where A.b = B.b

題目不再贅述,資料庫如下:

taxauthorities表

taxauthorities表

taxrates表

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