The forum will experience an outage sometime between February 10 at 7:00pm EST and February 12 at 11:59 EST for installation of security updates. The actual time and duration of the outage are unknown but attempts will be made to minimize the downtime. We apologize for any inconvenience.

I'd like a query that returns the first two sales for EACH salesperson ordered by date from a main sales table. Each person may have made many sales but I just want the first n when ordered by date.

E.g.

salesperson_id, salesperson_name, sale_id, saledate
1,Tim,1,2011-01-01
1,Tim,2,2011-01-02
3,Fred,1,2011-05-01
3,Fred,2,2011-05-01
4,Julie,1,2011-05-10
4,Julie,2,2011-05-10

asked 06 Dec '11, 15:00

TimC's gravatar image

TimC
1515610
accept rate: 0%

edited 07 Dec '11, 03:37

Volker%20Barth's gravatar image

Volker Barth
29.3k287438644


permanent link

answered 06 Dec '11, 15:06

Breck%20Carter's gravatar image

Breck Carter
26.6k418575824
accept rate: 21%

Thanks Breck, I've used Rank in other reports but find it can return more records than required when multiple results have the same value. In this instance, I require 2 for each sales person. No more.

(06 Dec '11, 16:00) TimC
Replies hidden

IMHO, given Breck's sample, that would mean that a single sales person has more than 2 sales on the same date - how are you going to treat that?

If this doesn't occur in your data, then I wouldn't expect problems with RANK() - as it should be used with a partition on each sales person...

BTW, ROWNUMBER() should resolve "ties".

(06 Dec '11, 16:13) Volker Barth
1

That's what the WHERE clause is for, in your case WHERE ranked.entry_rank <= 2.

(06 Dec '11, 16:14) Breck Carter

ROW_NUMBER() resolved it.

Top answer by Breck and Volker. Many thanks.

(06 Dec '11, 17:18) TimC
Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Question tags:

×46
×15

question asked: 06 Dec '11, 15:00

question was seen: 817 times

last updated: 07 Dec '11, 03:37