2013-11-10 53 views
0

我有一個表,看起來像這樣:MySQL的高級點心查詢

+--------------+------------+-------------+ 
| TaxAuthority | Effective | AuthTaxRate | 
+--------------+------------+-------------+ 
| city1  | 1993-01-01 |   1.0 | 
| city1  | 1994-01-01 |   1.5 | 
| city2  | 1993-09-01 |   1.5 | 
| city2  | 1994-01-01 |   2.0 | 
| city2  | 1995-01-01 |   2.5 | 
| city3  | 1993-01-01 |   1.9 | 
| city3  | 1993-07-01 |   2.3 | 
| county1  | 1993-01-01 |   2.3 | 
| county1  | 1994-10-01 |   2.5 | 
| county1  | 1995-01-01 |   2.7 | 
| county2  | 1993-01-01 |   2.4 | 
| county2  | 1994-01-01 |   2.7 | 
| county2  | 1995-01-01 |   2.8 | 
| state1  | 1993-01-01 |   0.5 | 
| state1  | 1994-01-01 |   0.8 | 
| state1  | 1994-07-01 |   0.9 | 
| state1  | 1994-10-01 |   1.1 | 
+--------------+------------+-------------+ 

我想在11月1日1994年選擇稅率城2例:

City2 = 2.0 
County1=2.5 
State1=1.1 
Total=5.6 

到目前爲止,我已經能夠得到加起來爲5.6的所有金額;但是,我不知道如何加總這三筆錢。這是我至今聲明:

select AuthTaxRate 
    from TaxRates 
    where TaxAuthority = 'City2' 
    and Effective <= '1994-11-01' 
    and Effective > '1993-09-01' 
    union 
    select AuthTaxRate 
    from TaxRates 
    where TaxAuthority = 'County1' 
    and Effective <= '1994-11-01' 
    and Effective > '1993-09-01' 
    union 
    select AuthTaxRate 
    from TaxRates 
    where TaxAuthority = 'State1' 
    and Effective <= '1994-11-01' 
    and Effective > '1994-07-01'; 

我發言的結果是:

+-------------+ 
| AuthTaxRate | 
+-------------+ 
|   2.0 | 
|   2.5 | 
|   1.1 | 
+-------------+ 

有誰知道如何添加了這些價值?

+2

'選擇總和(AuthTaxRate)...' – 2013-11-10 01:51:49

+0

呃 - 你怎麼知道是哪個城市,其中縣? (以及跨越多個縣城的情況如何) – Strawberry

回答

0

我現在知道,但你可以從TaxRates嘗試像這個 -

Select sum( 
select AuthTaxRate 
    from TaxRates 
    where TaxAuthority = 'City2' 
    and Effective <= '1994-11-01' 
    and Effective > '1993-09-01' 
    union 
    select AuthTaxRate 
    from TaxRates 
    where TaxAuthority = 'County1' 
    and Effective <= '1994-11-01' 
    and Effective > '1993-09-01' 
    union 
    select AuthTaxRate 
    from TaxRates 
    where TaxAuthority = 'State1' 
    and Effective <= '1994-11-01' 
    and Effective > '1994-07-01'; 
) As total;