Reputation: 89
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!
Upvotes: 1
Views: 4552
Reputation: 117370
you don't need to use subquery
select
[ACCOUNT ID],
SUM(PROFIT)
from [Transaction Table]
where [ACCOUNT ID] in ('1001','2001') and [ACTIVITY DATE] in ('5/31/2012')
group by [ACCOUNT ID]
your query just counted sum for two accounts and showed it in each row
update:
Actually for multiple sums I'd do something like this
select
[ACCOUNT ID],
SUM(case when [ACTIVITY DATE] in ('5/31/2012') then PROFIT else 0 end) as 'May Profit',
SUM(case when [ACTIVITY DATE] in ('4/31/2012') then PROFIT else 0 end) as 'April Profit'
from [Transaction Table]
where [ACCOUNT ID] in ('1001','2001') and
group by [ACCOUNT ID]
Upvotes: 2
Reputation: 21312
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:
select
[ACCOUNT ID],
(
select SUM(PROFIT)
from [Transaction Table]
where [ACCOUNT ID] = T.[ACCOUNT ID]
and [ACTIVITY DATE] in ('5/31/2012')
) as 'May Profit'
from
[Transaction Table] T
where
[ACCOUNT ID] in ('1001','2001')
group by
[ACCOUNT ID]
A better way:
select
[ACCOUNT ID],
SUM(PROFIT)
from [Transaction Table]
where [ACCOUNT ID] in ('1001','2001') and [ACTIVITY DATE] in ('5/31/2012')
group by [ACCOUNT ID]
Upvotes: 0