比较行号1和行号2之间的一个列值

时间:2018-06-07 15:17:25

标签: sql oracle

例如,我有下表basket

basket fruit   quantity
1      mango   2
1      apple   2
2      banana  2
2      banana  3
2      banana  3

现在我必须找到有超过1行的篮子,并且篮子中的类型彼此不同。所以1号篮子应该出来了。

我写了以下SQL:

select count(*),c.basket from baskets c group by c.basket having count(*)>1;

但是在这之后我怎么能得到水果类型在行之间彼此不同的篮子?在这种情况下,它应该是1号篮子。

3 个答案:

答案 0 :(得分:1)

我会使用min()max()

select b.basket
from baskets b
group by b.basket
where min(b.fruit) <> max(b.fruit);

答案 1 :(得分:1)

只需添加到HAVING子句:

select count(*), c.basket 
  from baskets c 
 group by c.basket 
having count(*)>1 
   AND COUNT(DISTINCT fruit)>1;

答案 2 :(得分:0)

我会使用exists

select b.*
from baskets b
where exists (select 1 
              from baskets b1 
              where b1.basket = b.basket and 
                    b1.fruit <> b.fruit
            );