在父表和子表上查看查询

时间:2013-01-24 07:17:58

标签: sql view oracle10g oracle11g

我使用的是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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)); 

答案 2 :(得分: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

答案 3 :(得分: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
                )
            );