[Webinar] Streamline your web hosting managementRegister Today

x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 1083

Union Two Columns and Sum in Same Table?

Don't know how to successfully union these seperate queries. These two queries return a sum of counts per user, either In or Out

Select UserOut, sum(Sent) as [sent], sum(rcvd) as [Received] from table1 t1
Join table2 on UserName = t1.UserOut
Group By UserOut

Select UserIn, sum(Sent) as [sent], sum(rcvd) as [Received] from table1 t1
Join table2 on UserName = t1.UserIn
Group By UserIn
0
pointeman
• 4
• 2
1 Solution

Commented:
try this:

Select UserOut, sum(Sent) as [sent], sum(rcvd) as [Received], 'Out' as direction
from
table1 t1
Join table2 on UserName = t1.UserOut
Group By UserOut
union all
Select UserIn, sum(Sent) as [sent], sum(rcvd) as [Received], 'In'
from table1 t1
Join table2 on UserName = t1.UserIn
Group By UserIn
0

Author Commented:
That's better, but I still have dups like so: (maybe a union is not the answer)
[Result]
Bob    555    1221
Bob    333      333
Joe         0           0
Joe         0           0
0

Commented:
from
(
Select UserOut, sum(Sent) as [sent], sum(rcvd) as [Received]
from
table1 t1
Join table2 on UserName = t1.UserOut
Group By UserOut
union all
Select UserIn, sum(Sent) as [sent], sum(rcvd) as [Received]
from table1 t1
Join table2 on UserName = t1.UserIn
Group By UserIn
) a
group by userout
0

Author Commented:

Removing , sum(sent), sum(received) from the first row removed the error, but also returns the following:

Error:
Invalid column name 'sent'.
Invalid column name 'rcvd'.

Return:
Bob
Joe

select userout
from
(
Select UserOut, sum(Sent) as [sent], sum(rcvd) as [Received]
from
table1 t1
Join table2 on UserName = t1.UserOut
Group By UserOut
union all
Select UserIn, sum(Sent) as [sent], sum(rcvd) as [Received]
from table1 t1
Join table2 on UserName = t1.UserIn
Group By UserIn
) a
group by userout
0

Data EngineerCommented:
Why did you remove that from chapmandew's query. chapmandew's query should give you the desired result. I did a minor modiification to his solution.

select a.user,sum(a.sent),sum(a.rcvd)
from
(
Select UserOut as user, sum(Sent) as [sent], sum(rcvd) as [Received]
from
table1 t1
Join table2 on UserName = t1.UserOut
Group By UserOut
union all
Select UserIn as user, sum(Sent) as [sent], sum(rcvd) as [Received]
from table1 t1
Join table2 on UserName = t1.UserIn
Group By UserIn
)  as a
group by a.user
0

Author Commented:
Yours doesn't work correctly either.
I've continued with the query and found the solution.

0

Author Commented:
Here is the correct method I've found: (had to change the Join to a Where clause)

Select UserOut, sum(Sent) as [sent], sum(Rcvd) as [received]
From
(
Select UserOut, Sent, Rcvd From table1 Where Exists
(
)
Union All
Select UserIn, Sent, Rcvd From table1 Where Exists
(