我想制定一个返回vin
,customer_id
和model_id
的查询,其中相同 customer_id
多个来自model_id
表的{{1>}“ toyota ”的记录。主键中的CAR
且唯一。有任何想法吗?我正在使用Oracle 10g。
CAR表:
vin
数据:
vin varchar (primary key)
customer_id varchar
model_id varchar
答案 0 :(得分:1)
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
<强> Results 强>:
| 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
<强> Results 强>:
| VIN | CUSTOMER_ID | MODEL_ID |
--------------------------------------
| 123232SSS | cust1234 | toyota |
| 222313XYZ | cust1234 | toyota |