包装查询以获得大于3的计数

时间:2015-12-18 15:25:52

标签: sql oracle

SELECT ownerid, zip, vin, make, model FROM listing 
WHERE (ownerid, upper(make)) 
IN (SELECT dealership, attribute FROM ownerproduct WHERE productid = 'FRONT_LISTING')
AND new = 'Y'
ORDER BY DBMS_RANDOM.RANDOM;

我的查询产生了front_listing。现在看来,它只产生大约85%的时间,所以我需要包装我的查询以获得ownerid,make,model的计数大于3,以便我的查询结果产生front_listing 100%的时间。

编辑:

所以我需要一个查询,其中至少有3个与ownerid和make关联的模型。因此,例如,所有者ID可能具有小于3的模型量,但是相同的模型可能具有不同的所有者ID,其具有大于3的计数,因此为什么我需要所有者,制造和模型的计数/数量大于3。

2 个答案:

答案 0 :(得分:2)

这是你的意思吗?

SELECT ownerid, zip, vin, make, model 
FROM 
(
SELECT ownerid, zip, vin, make, model, count(*) over (partition by ownerid, make, model) cnt FROM listing 
WHERE (ownerid, upper(make)) 
IN (SELECT dealership, attribute FROM ownerproduct WHERE productid = 'FRONT_LISTING')
AND new = 'Y'
)
WHERE cnt > 3
ORDER BY DBMS_RANDOM.RANDOM );

答案 1 :(得分:1)

我不确定使用这种WHERE子句查询的效率如何:

 WHERE (ownerid, upper(make)) 
    IN (SELECT dealership, attribute FROM ownerproduct WHERE productid = 'FRONT_LISTING')

我会尝试这样的事情:

SELECT ownerid, zip, vin, make, model FROM (
    SELECT op.dealership AS ownerid, l.zip, l.vin, l.make, l.model
         , COUNT(*) OVER ( PARTITION BY op.dealership, l.make, l.model) cnt
      FROM ownerproduct op INNER JOIN listing l
        ON op.dealership = l.ownerid
       AND op.attribute = UPPER(l.make)
     WHERE op.productid = 'FRONT_LISTING'
       AND l.new = 'Y'
) WHERE cnt >= 3
 ORDER BY DBMS_RANDOM.VALUE;

P.S。我使用DBMS_RANDOM.VALUE而不是DBMS_RANDOM.RANDOM的原因是后者已被弃用(自11gR1起)。