2015-04-02 38 views
0

我需要开发一个脚本,将捕获所有领域时,一辆车被绑定到多种颜色。选择基于一个字段关联与另一个字段中的多个值

如果一辆车不止一次绑定一种颜色,只有当该汽车被绑上其他颜色时才需要捕获。

如果一辆车多次绑定一种颜色,并且不需要捕获其他颜色。

{CREATE TABLE test2 
(
    ID  NUMBER(9), 
    CAR NUMBER(9), 
    COLOR NUMBER(9) 
); 


Insert into test2 (ID, CAR, COLOR) Values (1, 5, 10); 
Insert into test2 (ID, CAR, COLOR) Values (2, 5, 11); 
Insert into test2 (ID, CAR, COLOR) Values (3, 5, 10); 
Insert into test2 (ID, CAR, COLOR) Values (4, 9, 6); 
Insert into test2 (ID, CAR, COLOR) Values (5, 9, 6); 
Insert into test2 (ID, CAR, COLOR) Values (6, 8, 4); 
Insert into test2 (ID, CAR, COLOR) Values (7, 8, 9); 
Insert into test2 (ID, CAR, COLOR) Values (8, 12, 9); 
COMMIT;} 



--expected results 
    ID   CAR   COLOR 
    1   5    10 
    2   5    11 
    3   5    10 
    6   8    4 
    7   8    4 

所有见解和建议深表赞赏。

回答

0

我会用任何一个in条款或相关exists条款。后者应履行好于前者:

select id, car, color from test2 
where car in (
    select car 
    from test2 
    group by car 
    having count(distinct color) > 1 
) 

select id, car, color from test2 t 
where exists (
    select car 
    from test2 
    where car = t.car 
    group by car 
    having count(distinct color) > 1 
) 

Sample SQL Fiddle

+0

很好。在编写查询时考虑到所有的特性非常重要,我只是在编写答案的时候记住了(明确的),而我经常使用它。 – jfun 2015-04-02 16:42:11

+1

jpw,这很好,对更大的真实的例子。谢谢! – user761758 2015-04-02 16:45:26

0

您需要执行count两次:

with cte as 
( select CAR,COLOR,count(*) cn 
    from test2 
    group by CAR,COLOR 
) 
select t.id,t.car,t.color 
from test2 t 
join( 
    select car,count(*) 
    from cte 
    group by CAR 
    having count(*)>1)q 
on t.car=q.car 
order by 1 

OUTPUT:

ID CAR COLOR 
1 5 10 
2 5 11 
3 5 10 
6 8 4 
7 8 9 
0

我认为你需要,除了那些所有的车都只有一个不同的颜色:
(替代其他的答案,但很简单)

select * 
from test2 
where not car in (select car from test2 group by car having count(distinct color = 1)) 
相关问题