2015-04-02 73 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)) 
相關問題