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 |
|
ewomack
Starting Member
33 Posts |
Posted - 2010-09-09 : 09:42:46
|
Hello,I'm currently struggling with this one. I have a bunch of IDs (each representing 1 person) that each have 1 or more accounts that they have dollar amounts for. I need to find the largest amount for each id given a particular fund. A sample will probably help demonstrate:ID account amount-- ------- ------02 1234567 $100.0002 2345678 $50.0002 3456789 $2000.0002 4567890 $75.0015 1234567 $1000.0015 2345678 $500.0015 3456789 $25.0015 4567890 $700.00I have a collection of groupings like the above chart and need to find all id#s who have their largest amount in a particular account. So, for instance, I need to list all ids who have their largest amount as account "3456789." Running this query against the data above would return ID 02 (since account 3456789 has the largest amount of all other accounts), but not ID 15.My instinct tells me variables and looping, so that's where I'm starting. Has anyone else had to SQL this issue?Thank you! Ed Womackwww.getmilked.com |
|
|
ewomack
Starting Member
33 Posts |
Posted - 2010-09-09 : 09:57:54
|
| I thought of one solution involving temp tables, but I'd rather avoid it if I can. Insert the following query into a tableinsert into stinking_temp_table(ID, account, amount)select ID, account, max(amount)from tablegroup by ID, accountorder by IDThen query this tableselect ID, account, amountfrom stinking_temp_tablewhere account in ('3456789')This should at least give me everyone with a max amount in that account.Ed Womackwww.getmilked.com |
 |
|
|
ewomack
Starting Member
33 Posts |
Posted - 2010-09-09 : 10:02:25
|
Nope, this just moves the problem. I'll stop thinking online... Ed Womackwww.getmilked.com |
 |
|
|
parody
Posting Yak Master
111 Posts |
Posted - 2010-09-09 : 11:44:33
|
| are you always specifying the account?if so:select top 1 IDfrom tablewhere account = ?order by amount desc |
 |
|
|
parody
Posting Yak Master
111 Posts |
Posted - 2010-09-09 : 11:47:57
|
| this raises some Q's on what you would do if 2 ID's had the same amount. I'd probably use a ranking function and take where rank = 1 top get all of them if requiredi.e:with cte as(select ID,rank() over (partition by amount order by amount desc) as rankfrom tablewhere account = ?)select * from cte where rank = 1all on the fly might be some syntax amiss! |
 |
|
|
|
|
|
|
|