Oracle 10g在查询中选择

时间:2012-11-16 16:48:54

标签: sql oracle

我想制定一个返回vincustomer_idmodel_id的查询,其中相同 customer_id 多个来自model_id表的{{1>}“ toyota ”的记录。主键中的CAR且唯一。有任何想法吗?我正在使用Oracle 10g。

CAR表:

vin

数据:

vin varchar (primary key)
customer_id varchar
model_id varchar

1 个答案:

答案 0 :(得分:1)

SQL Fiddle

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 |