0

我想制定一个返回vin,的查询customer_idmodel_id其中相同 customer_id条记录具有表model_id中的“丰田CAR。中的vin主键且唯一。有任何想法吗?我正在使用 Oracle 10g。

汽车表:

vin varchar (primary key)
customer_id varchar
model_id varchar

数据:

vin        customer_id   model_id 
------------------------------------  
222313XYZ,   cust1234,   toyota
123232SSS,   cust1234,   toyota
111111ERE,   cust1111,   bmw
999999LKO,   cust1224,   bmw
4

1 回答 1

1

SQL小提琴

Oracle 11g R2 模式设置

CREATE TABLE car
    (vin varchar2(9), customer_id varchar2(8), model_id varchar2(6))
;

INSERT ALL 
    INTO car (vin, customer_id, model_id)
         VALUES ('222313XYZ', 'cust1234', 'toyota')
    INTO car (vin, customer_id, model_id)
         VALUES ('123232SSS', 'cust1234', 'toyota')
    INTO car (vin, customer_id, model_id)
         VALUES ('111111ERE', 'cust1111', 'bmw')
    INTO car (vin, customer_id, model_id)
         VALUES ('999999LKO', 'cust1234', 'bmw')
SELECT * FROM dual
;

查询 1:如果您想查看其所有者还拥有多个丰田的所有模型

select vin, customer_id, model_id from (
 select vin, customer_id, model_id, 
 count( decode(model_id, 'toyota', 1) ) over (partition by customer_id) cnt
  from car
)
where cnt > 1

结果

|       VIN | CUSTOMER_ID | MODEL_ID |
--------------------------------------
| 999999LKO |    cust1234 |      bmw |
| 222313XYZ |    cust1234 |   toyota |
| 123232SSS |    cust1234 |   toyota |

查询 2:如果您只想查看拥有多个所有者的丰田汽车:

select vin, customer_id, model_id from (
 select vin, customer_id, model_id, 
 count(*) over (partition by customer_id) cnt
  from car
 where model_id = 'toyota'
)
where cnt > 1

结果

|       VIN | CUSTOMER_ID | MODEL_ID |
--------------------------------------
| 123232SSS |    cust1234 |   toyota |
| 222313XYZ |    cust1234 |   toyota |
于 2012-11-16T17:08:23.640 回答