1

我正在使用 Oracle 11G,我有下面的表结构

STATE_DEF 表是父表

TAX_DEF_ID  EFFECTIVE_DATE  REP_TYPE
1           9-Jan-12        R
2           15-Jan-12       W

和子表'TAX_DETAIL'如下

TAX_DETAIL_ID   TAX_TYPE    DISTRIBUTION_TYPE   WH_RATE   TAX_DEF_ID
1               I           S                   0.1       1
2               I           P                   0.12      1
3               D           S                   0.2       1
4               D           P                   0.22      1
5               I           S                   0.3       2
6               I           P                   0.31      2
7               D           S                   0.4       2
8               D           P                   0.41      2

我想创建一个视图,它将给出如下所示的输出

TAX_DEF_ID  EFFECTIVE_DATE  I_S_WH_RATE    I_P_WH_RATE  D_S_WH_RATE   D_P_WH_RATE
1           9-Jan-12        0.1            0.12         0.2           0.22
2           15-Jan-12       0.3            0.31         0.4           0.41

我尝试过 LISTAGG 函数,但它会给我一个带有连接列的列。我正在寻找视图定义,它将在单独的列中为我提供有效日期的费率。

我一直试图从几天内获得这个输出。我会感谢任何帮助来实现上述结果。

4

4 回答 4

1

试试这个:

SELECT
    SD.TAX_DEF_ID,
    SD.EFFECTIVE_DATE,
    SUM(CASE WHEN TAX_TYPE = 'I' AND DISTRIBUTION_TYPE = 'S' THEN WH_RATE ELSE 0 END) I_S_WH_RATE,
    SUM(CASE WHEN TAX_TYPE = 'I' AND DISTRIBUTION_TYPE = 'P' THEN WH_RATE ELSE 0 END) I_P_WH_RATE,
    SUM(CASE WHEN TAX_TYPE = 'D' AND DISTRIBUTION_TYPE = 'S' THEN WH_RATE ELSE 0 END) D_S_WH_RATE,
    SUM(CASE WHEN TAX_TYPE = 'D' AND DISTRIBUTION_TYPE = 'P' THEN WH_RATE ELSE 0 END) D_P_WH_RATE
FROM STATE_DEF SD
    LEFT JOIN TAX_DETAIL TD
        ON SD.TAX_DEF_ID = TD.TAX_DEF_ID
GROUP BY SD.TAX_DEF_ID, SD.EFFECTIVE_DATE
于 2013-01-24T07:24:54.250 回答
1

请使用检查结果PIVOT

select * From(
  select 
    a.TAX_DEF_ID, 
    a.EFFECTIVE_DATE, 
    TAX_TYPE||DISTRIBUTION_TYPE AS TYP, 
    WH_RATE 
  From STATE_DEF a INNER JOIN TAX_DETAIL b ON a.TAX_DEF_ID=b.TAX_DEF_ID
)x 
PIVOT
(MAX(WH_RATE) as WH_RATE for (TYP) IN ('IS' AS I_S, 'IP' as I_P, 'DS' as D_S, 'DP' as D_P)); 
于 2013-01-24T07:44:21.400 回答
0
select 
  tax_def_id,
  effective_date,
  sum(case when d.tax_type='I' and d.distribution_type='S' then wh_rate end) as I_S_WH_RATE
  --and so on...
from state_def t
join tax_detail d on (t.tax_def_id = d.tax_def_id)
group by   
   tax_def_id, 
   effective_date
于 2013-01-24T07:23:38.190 回答
0

在 11g 中,您可以对此进行调整:

with data as (select s.TAX_DEF_ID, s.EFFECTIVE_DATE, d.TAX_TYPE, d.DISTRIBUTION_TYPE, d.WH_RATE
                from state_def s
                     inner join tax_detail d
                             on s.tax_def_id = d.tax_def_id)
select *
  from data
       pivot(max(wh_rate)
             for (TAX_TYPE, DISTRIBUTION_TYPE)
             in (('I', 'S') as I_S_WH_RATE,
                 ('I', 'P') as I_P_WH_RATE,
                 ('D', 'S') as D_S_WH_RATE,
                 ('D', 'P') as D_P_WH_RATE
                )
            );
于 2013-01-24T07:27:44.200 回答