Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
funk.phenomena
Posting Yak Master
121 Posts |
Posted - 2012-08-02 : 15:32:10
|
| Hi All - I have the following table[CODE]REP SALES LOCATIONJohn 20 NewYorkJohn 50 ChicagoAlex 40 BostonAlex 50 LosAngelesAdam 20 WichitaAdam 10 Miami[/CODE]I would like it to output the rep and their sales just ONCE, based on the highest sales for that city. For example, it would output the following:[CODE]REP SALES LOCATIONJohn 50 ChicagoAlex 50 LosAngelesAdam 20 Wichita[/CODE]I thought this can be acheived through a simple GROUP BY statement, but I'm doing it wrong:[CODE]SELECT REP, SALES, LOCATIONFROM SALES_TABLEGROUP BY REP, SALES, LOCATIONHAVING MAX(SALES)[/CODE]Thanks! |
|
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-08-02 : 15:42:20
|
You can use ROW_NUMBER() function to do this like this:SELECT REP, SALES, LOCATIONFROM( SELECT *, ROW_NUMBER() OVER (PARTITION BY REP ORDER BY Sales DESC) AS RN FROM SalesTable) sWHERE RN = 1; |
 |
|
|
funk.phenomena
Posting Yak Master
121 Posts |
Posted - 2012-08-02 : 15:51:15
|
| Worked, Thanks!!!!!!!!!!!!!!!!!!! :) |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-08-02 : 16:07:56
|
| [code]SELECT Rep,Sales,LocationFROM (SELECT *,MAX(Sales) OVER (PARTITION BY Rep) AS MaxSalesFROM table)tWHERE Sales=MaxSales[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|
|