2014-02-18 74 views
0

我試圖轉動的狀態稅表,Mysql的數據透視表與案件

源表

+------------+-----------+------------------+----------+ 
| state_code | threshold | filing_status | tax_rate | 
+------------+-----------+------------------+----------+ 
| AK   |  9000 | Head of Househol | 0.000 | 
| AK   |  19000 | Married   | 0.000 | 
| AK   |  8000 | Single   | 0.000 | 
| AL   |   0 | Head of Househol | 2.000 | 
| AL   |   0 | Married   | 2.000 | 

選擇

select 
    P.state_code, 
    P.tax_rate, 
    case when P.filing_status = 'Married' then threshold end as 'Married', 
    case when P.filing_status = 'Single' then threshold end as 'Single' 
from state_tax_bracket P; 

將每比返回多行

+------------+----------+-------------------+---------+---------+ 
| state_code | tax_rate | Head of Household | Married | Single | 
+------------+----------+-------------------+---------+---------+ 
| AR   | 7.000 |    32600 | NULL | NULL | 
| AR   | 7.000 |    NULL | 52600 | NULL | 
| AR   | 7.000 |    NULL | NULL | 21600 | 

但期望的結果是每個比率一行和所有狀態值

+------------+----------+-------------------+---------+---------+ 
| state_code | tax_rate | Head of Household | Married | Single | 
+------------+----------+-------------------+---------+---------+ 
| AR   | 7.000 |    32600 | 52600 | 21600 | 

無程序。

回答

1

你可以使用MAX和IFNULL這樣的:

MAX(IFNULL(閾值,NULL))。

Eddie。

+0

不要..,如果多個國家/稅率忘記組? – DRapp

+0

'ifnull('...',NULL)'意味着什麼? – SingleNegationElimination

1

如果有人尋找同樣的我已經找到了解決辦法:

select 
t.state_code, 
t.state_name, 
sum(t.Single) as 'single', 
sum(Married) as 'married', 
sum(`Head of Household`) as 'head', 
t.tax_rate as 'tax_rate' 
from ( 
    select 
    P.state_code, 
    S.state_name, 
    P.tax_rate, 
    case when P.filing_status = 'Head of Househol' then threshold end as 'Head of Household', 
    case when P.filing_status = 'Married' then threshold end as 'Married', 
    case when P.filing_status = 'Single' then threshold end as 'Single' 
     from 
     state_tax_bracket P, 
     state_tax S 
     where 
     P.state_code = S.state_code) 
    as t 
    group by tax_rate;