Question

I know this is going to be a simple one but after a midnight run at other coding my SQL brain is fried so I'm just reaching out for some quick help. I've got a test table with Agent, AgentID, Parent Account, AccountID, and TCV. What I need to do is pull all the agent/account IDs where the AccountIDs belong to an aggregate parent account under that agents name >= 10K.

enter image description here

So in this example, John has 2 accounts under the parent account ABC123 and since their total value is >=10K, these 2 would get pulled. But notice below where Jane has 2 accounts likewise under ABC123 but b/c their total value in her name is < 10K, they would not be pulled. So the results would be something like this:

enter image description here

Essetially I need to pull all AccountIDs where the total value of the parent account they roll-up to for that person is >= 10K. BTW, I'm using SQL Server Management Studio R2.

Was it helpful?

Solution

You just do a simple group by/having to get a list of agentids/parentaccounts that meet the 10k criteria. Then you can use that in a sub-select to join back to the same table and get the list of account ids

select agentid, accountid
from table t
inner join (
  select agentid, parentaccount
  from table
  group by agentid, parentaccount
  having sum(tcv) >= 10000
) t1
  on t.agentid = t1.agentid
     and t.parentaccount = t1.parentaccount

OTHER TIPS

;WITH MyCTE AS
(
    SELECT AgentID,
           ParentAccount,
           SUM(TCV) AS Total
    FROM   TableName
    GROUP BY AgentID,
           ParentAccount
)

SELECT T.AgentId, T.AccountId
FROM   Table T
       JOIN MyCTE M
           ON M.AgentId = T.AgentId
           AND M.ParentAccount= T.ParentAccount
WHERE  M.Total>10000
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top