尝试创建SQL查询

时间:2015-11-10 16:20:48

标签: sql

我正在尝试创建一个查询,该查询仅检索六个月内拾取次数最多的十家公司,这意味着取件时间,而不是拾取的物品数量。 我做了这个

2 个答案:

答案 0 :(得分:1)

SELECT  * 
FROM    customer
JOIN (SELECT manifest.pickup_customer_ref reference,
             DENSE_RANK() OVER (PARTITION BY manifest.pickup_customer_ref ORDER BY COUNT(manifest.trip_id) DESC) rnk
      FROM   manifest 
      INNER JOIN trip ON manifest.trip_id = trip.trip_id
      WHERE trip.departure_date > TRUNC(SYSDATE) - interval '6' month
      GROUP BY manifest.pickup_customer_ref) cm ON customer.reference = cm.reference
WHERE cm.rnk < 11;

这使用dense_rank来确定首先出行次数最多的订单或客户

答案 1 :(得分:0)

嗯,我没有甲骨文,所以我不能100%测试它,但我相信你会找到类似下面的内容:

请记住,当您使用分组依据时,您必须缩小到选择中分组的相同字段。希望这有助于至少让您了解要查看的内容。

select TOP 10 
    c.company_name,
    m.pickup_customer_ref,
    count(*) as 'count'
from customer c
inner join mainfest m on m.pickup_customer_ref = c.reference
inner join trip t on t.trip_id = m.trip_id
where t.departure_date < DATEADD(month, -6, GETDATE())
group by c.company_name, m.pickup_customer_ref
order by 'count', c.company_name, m.pickup_customer_ref desc