0

I am trying to create a query that retrieves only the ten companies with the highest number of pickups over the six-month period, this means pickup occasions, and not the number of items picked up. I have done this

11
  • 1
    It will be useful to provide test data and expected results that we can use? an SQLFiddle would be nice. Good start with the table definitions. Commented Nov 10, 2015 at 16:24
  • Hi, its meant to return two rows. One called company_name (with the name of the company) and the other called pickups (number of pickups the company has completed. Commented Nov 10, 2015 at 16:25
  • Sample inserts and expected output (perhaps you could say "I want the top 2 pickups out of these 4 companies") would help us enormously to be able to help you. Commented Nov 10, 2015 at 16:26
  • I dont get "this means pickup occasions, and not the number of items picked up." this part , what exactly do you want ? Commented Nov 10, 2015 at 16:26
  • 1
    you should probably look at the Dense_Rank function techonthenet.com/oracle/functions/dense_rank.php Commented Nov 10, 2015 at 16:42

2 Answers 2

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;

this uses dense_rank to determine the order or customers with the highest number of trips first

Sign up to request clarification or add additional context in comments.

Comments

0

Hmm well i don't have Oracle so I can't test it 100%, but I believe your looking for something like the following:

Keep in mind that when you use group by, you have to narrow down to the same fields you group by in the select. Hope this helps at least give you an idea of what to look at.

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

2 Comments

Oracle doesn't support TOP, DATEADD() or GETDATE(); and column aliases can't be in single quotes...
I knew I hated oracle for a reason! :-) Well there are easy replacements for those if they are looked up, but the gist is still the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.