2016-09-20 135 views
0

我的表查询中的列不具有在另一列的值相同

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 

我想显示所有itemcodeAB不具有在列的值相同Total

我的预期结果

ItemCode   ItemName   Total 
---------------------------------------- 
A     name1    5 
A     name1    5 
B     name2    25 
B     name1    30 

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

+1

对我仍然没有这么清楚:为什么预期结果中ItemCode ='A'的行?它们来自完全相同的行,具有相同的Total,而您说“在Total列中没有相同的值”。你的意思是你只想要不存在一行不同的具有相同总数的ItemCode的行吗? – Aleksej

+0

@Aleksej嗨阿列克谢谢谢你真的帮助我。我想要的只是获得项目代码'A'和'B'中不具有相同'Total'的所有项目名称,但是如果它们在相同的项目代码中并且具有相同的总数,我希望它们包括在内。 –

+0

你只想要对A和B或每对如(A,C)(B,C)等 –

回答

1

假设你需要为不与同Total存在的不同itemCode另一行的行,并假设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 
+0

这实际上工作!感谢男人@Aleksej 5竖起大拇指! –

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
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