| Author |
Topic |
|
jmarkee
Starting Member
9 Posts |
Posted - 2009-05-08 : 21:29:35
|
| I need to do SQL Select command that filters the number of orders of a particular customer are displayed. My table has multple customers and multiple entries for a customers who have more than one purchase. I would like to have a query that shows me the last 5 orders for each customer?How would I do this?Thanks! |
|
|
jmarkee
Starting Member
9 Posts |
Posted - 2009-05-08 : 21:51:29
|
| For instance:TABLE:CustomerID Purchase---------- --------Jason Teddy BeadJason GorillaJason BikeJenny BikeDesired Result if I wanted top 2 record for a customerJason BikeJason GorillaJenny Bike |
 |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2009-05-08 : 22:09:11
|
| SELECT CustomerID, Purchase FROM myTable TWHERE T.Purchase IN(SELECT TOP 2 Purchase FROM myTable T2 WHERE T.CustomerID=T2.CustomerID ORDER BY T2.Purchase) |
 |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-05-09 : 04:35:23
|
quote: Originally posted by jmarkee For instance:TABLE:CustomerID Purchase---------- --------Jason Teddy BeadJason GorillaJason BikeJenny BikeDesired Result if I wanted top 2 record for a customerJason BikeJason GorillaJenny Bike
do you have a date column in your purchase table which designates when order was placed to find the last 5 orders? or if pk of table is purchaseid which i assume is identity field, you can use belowSELECT c.CustomerID,p.PurchaseFROM Customer cCROSS APPLY (SELECT TOP 5 Purchase FROM Purchase WHERE CustomerID=c.CustomerID ORDER BY PurchaseID DESC) p |
 |
|
|
jmarkee
Starting Member
9 Posts |
Posted - 2009-05-09 : 16:47:08
|
| Thanks Everyone. These worked! You guys rock. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-05-10 : 02:19:19
|
| welcome |
 |
|
|
jmarkee
Starting Member
9 Posts |
Posted - 2009-05-11 : 17:01:05
|
| One more follow up question. I simplified my question a bit but when I went to deploy i got stuck. I am doing all of this as part of a join statement. It would look something like this: SELECT CustomerID, Purchase, OtherPurhcaseInfo FROM myTable T INNER JOIN PURCHASE ON mytable.purchaseID = mypurchaseTable.PurchaseIDWHERE T.Purchase IN(SELECT TOP 2 Purchase FROM myTable T2 WHERE T.CustomerID=T2.CustomerID ORDER BY T2.Purchase)When I add the join statement in I cant seem to get this to work anymore.Thanks! |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-05-12 : 09:59:24
|
you're using wrong aliases. try this & see if it worksSELECT T.CustomerID, T.Purchase, T.OtherPurhcaseInfo FROM myTable T INNER JOIN PURCHASE PON T.purchaseID = P.PurchaseIDWHERE T.Purchase IN(SELECT TOP 2 T2.Purchase FROM myTable T2 WHERE T.CustomerID=T2.CustomerID ORDER BY T2.Purchase) |
 |
|
|
|