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 |