Having an issue with this sub query using SUM. The query will be totaling the profit column of several records from a specific date range. I am grouping this total profit by the account number attached to the record. With one account number, it works just fine:
select
[ACCOUNT ID],
(
select SUM(PROFIT)
from [Transaction Table]
where [ACCOUNT ID] in ('1001')
and [ACTIVITY DATE] in ('5/31/2012')
) as 'May Profit'
from
[Transaction Table]
where
[ACCOUNT ID] in ('1001')
group by
[ACCOUNT ID]
Gives correct results:
| ACCOUNT ID | May Profit |
---------------------------
| 1001 | $61.97 |
The trouble comes with multiple account numbers:
select
[ACCOUNT ID],
(
select SUM(PROFIT)
from [Transaction Table]
where [ACCOUNT ID] in ('1001','2001')
and [ACTIVITY DATE] in ('5/31/2012')
) as 'May Profit'
from
[Transaction Table]
where
[ACCOUNT ID] in ('1001','2001')
group by
[ACCOUNT ID]
Gives incorrect results:
| ACCOUNT ID | May Profit |
---------------------------
| 1001 | $127.34 |
| 2001 | $127.34 |
The “May Profit” is being totaled for both accounts on each record. I need individual profit totals per account number.
Any thoughts? Thanks in advance!
You don’t need to use a SubQuery, but here are 2 ways you can do it:
The first way, using your query (not recommended) – Notice the Account Id = T.Account Id:
A better way: