选择其他列

时间:2016-09-22 03:24:36

标签: sql oracle comparison aggregate-functions

我有这张桌子

type     item     yield    section
-----------------------------------
CT1   |    A   |   25   |   M-2
CT1   |    A   |   35   |   M-1
CT2   |    A   |   70   |   M-1
CT2   |    A   |   30   |   M-2
CT2   |    A   |   20   |   M-3
CT1   |    B   |   40   |   M-2
CT1   |    B   |   15   |   M-1
CT2   |    B   |   25   |   M-1
CT2   |    B   |   25   |   M-2

首先,我需要将所有yield加总Item and Type并将其除以表格中每行的每个产量。其次,我需要知道哪个yieldcosttypcd, item and section相同(IE type CT1 item A section M-1的收益率为.58(25 + 35 = 60然后35/60是.58)和type CT2 itemsection M-1的收益率也是.58所以我不想选择该项目,因为它匹配)。

到目前为止,我的代码只能获得收益(已经计算过,但无法确定如何只选择那些items中没有匹配的yield,item and section

select type,item,yield, section
FROM(
Select type, item,
       Round(yield/Sum(yield) Over (Partition By type,item),2) As yield,section
From MyTable
Order By item
)

所以我的问题是如何才能获得yield中只有item,section and different type匹配的所有项目?{/ 1}?

在我的表格中,CT1 A M-1CT2 A M-1的收益率匹配,因此我想选择所有剩余的项目。

预期产出:

type     item     section
--------------------------
CT1   |    A   |    M-2
CT2   |    A   |    M-2
CT2   |    A   |    M-3
CT1   |    B   |    M-2
CT1   |    B   |    M-1
CT2   |    B   |    M-1
CT2   |    B   |    M-2    

我不需要显示收益率。

1 个答案:

答案 0 :(得分:0)

with
     inputs ( type, item, yield, section ) as (
       select 'CT1', 'A', 25, 'M-2' from dual union all
       select 'CT1', 'A', 35, 'M-1' from dual union all
       select 'CT2', 'A', 70, 'M-1' from dual union all
       select 'CT2', 'A', 30, 'M-2' from dual union all
       select 'CT2', 'A', 20, 'M-3' from dual union all
       select 'CT1', 'B', 40, 'M-2' from dual union all
       select 'CT1', 'B', 15, 'M-1' from dual union all
       select 'CT2', 'B', 25, 'M-1' from dual union all
       select 'CT2', 'B', 25, 'M-2' from dual
     ),
     prep ( type, item, yield, section, pct ) as (
       select type, item, yield, section,
              yield / sum(yield) over (partition by type, item)
       from   inputs
     ),
     final ( type, item, yield, section, pct, ct ) as (
       select type, item, yield, section, pct, 
              count(distinct type) over (partition by item, section, pct)
       from   prep
     )
select type, item, section
from   final
where  ct = 1
;

输出:

TYPE ITEM SECTION
---- ---- -------
CT2  A    M-2
CT1  A    M-2
CT2  A    M-3
CT1  B    M-1
CT2  B    M-1
CT2  B    M-2
CT1  B    M-2

7 rows selected.