基于一个字段关联选择另一个字段中的多个值

时间:2015-04-02 15:44:36

标签: sql oracle

我需要开发一个脚本,当一辆车被绑定到多种颜色时,它将捕获所有字段。

如果一辆车多次绑在一种颜色上,那么只有当该车与其他颜色相连时才需要捕捉。

如果一辆车多次绑在一种颜色上,并且没有其他颜色不需要捕捉。

  {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

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

3 个答案:

答案 0 :(得分: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

输出:

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

答案 1 :(得分: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

答案 2 :(得分:0)

我认为你需要所有汽车,除了那些只有一种颜色的汽车:
(替代其他答案,但非常简单)

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