查询在另一列中没有相同值的列

时间:2016-09-20 08:26:29

标签: sql oracle join oracle11g self-join

我的表

ItemCode      ItemName       Total
----------------------------------
A              name1          5
A              name1          5
A              name2          10
B              name1          10 
B              name2          25
B              name1          30
C              name2          5
C              name1          30
C              name1          20

我希望显示itemcode列中A

列中所有B TotalItemCode ItemName Total ---------------------------------------- A name1 5 A name1 5 B name2 25 B name1 30

我的预期结果

regex

我已经问过这个问题了,但这一次我的问题比我上一次提问要清楚得多。我认为1解决方案是自我加入,但我无法弄明白。任何帮助对我来说意味着很多,谢谢!

3 个答案:

答案 0 :(得分:1)

尝试此查询:

select i.*
from my_table i
where i.ItemCode in ('A','B')
and (select count(*) from my_table t where t.ItemCode in ('A','B') 
and t.ItemCode != i.ItemCode and t.total = i.total) = 0

答案 1 :(得分:1)

假设您需要的行不存在具有相同itemCode的不同Total的另一行,并且假设ItemCode始终不为空,则一个简单的解决方案可以是这样的:

with test(ItemCode, ItemName, Total) as 
(
    select 'A', 'name1', 5  from dual union all
    select 'A', 'name1', 5  from dual union all
    select 'A', 'name2', 10 from dual union all
    select 'B', 'name1', 10 from dual union all
    select 'B', 'name2', 25 from dual union all
    select 'B', 'name1', 30 from dual union all
    select 'C', 'name2', 5  from dual union all
    select 'C', 'name1', 30 from dual union all
    select 'C', 'name1', 20 from dual
)
select *
from test t1
where ItemCode in ('A', 'B')
  and not exists (
                   select 1
                   from test t2
                   where t1.total    =  t2.total
                     and t1.itemCode != t2.itemCode
                     and ItemCode in ('A', 'B')
                 )

以下内容更快,但可读性更低:

select ItemCode, ItemName, Total
from (
        select ItemCode, ItemName, Total, count(distinct ItemCode) over (partition by Total) as itemCount
        from test
        where ItemCode in ('A', 'B')
     )
where itemCount = 1  

答案 2 :(得分:1)

SELECT A.* FROM (SELECT * FROM MYTABLE WHERE ITEMCODE='A')A
       LEFT JOIN (SELECT * FROM MYTABLE WHERE ITEMCODE='B')B ON
    A.TOTAL=B.TOTAL
WHERE B.ITEMCODE IS NULL

UNION

SELECT B.* FROM (SELECT * FROM MYTABLE WHERE ITEMCODE='B')B
       LEFT JOIN (SELECT * FROM MYTABLE WHERE ITEMCODE='A')A ON
    B.TOTAL=A.TOTAL
WHERE A.ITEMCODE IS NULL