Donate SIGN UP

SQL Question (First 3 records per field)

Avatar Image
Chris100682 | 15:42 Mon 14th Apr 2008 | Computers
4 Answers
Hi,

How do I write my SQL query to pull the first 2 account numbers per promo no?? Please help me!!!

I have the attached table:

+--------+----------+
| promo | account |
+--------+----------+
| 22054 | 412986 |
| 22054 | 412987 |
| 22054 | 412988 |
| 22054 | 412989 |
| 22055 | 412990 |
| 22055 | 412991 |
| 22055 | 412992 |
| 22055 | 412993 |
| 22055 | 412994 |
| 22066 | 412995 |
| 22066 | 412996 |
| 22066 | 412997 |
| 22077 | 412998 |
| 22077 | 412999 |
| 22077 | 413000 |
| 22077 | 413001 |
| 22077 | 413002 |
+--------+----------+

Many Thanks
Chris
Gravatar

Answers

1 to 4 of 4rss feed

Best Answer

No best answer has yet been selected by Chris100682. Once a best answer has been selected, it will be shown here.

For more on marking an answer as the "Best Answer", please visit our FAQ.
mmm... there is a way ive done it before, but fogotten, i'll try and find it but a simple way would be.

select promo,min(account),max(account) from mytable
group by promo

which will output
22054 412986 412989
22055 412990 412994
22066 412995 412997
22077 412998 413002

ok not the first two, but two per promocode.
ok found it

would be in the form:

select promo,account
from mytable
where (select count(*) from mytable as f
where f.promo = mytable.promo and f.account < mytable.account
) < 2

this will output

22054 412986
22054 412987
22055 412990
22055 412991
22066 412995
22066 412996
22077 412998
22077 412999

hope this helps!
oh yeah forgot to say the 2 at the end is the number of records you want returned per promocode
so if you change it to 3, the first 3 per promocode will be out put and so on.
Question Author
Thanks - A great help!!

1 to 4 of 4rss feed

Do you know the answer?

SQL Question (First 3 records per field)

Answer Question >>

Related Questions

Sorry, we can't find any related questions. Try using the search bar at the top of the page to search for some keywords, or choose a topic and submit your own question.