Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to merge two queries in sql
my two queries are:

first query is:
SQL
select b.UserName as USER_NAME, sum(a.TotalCount)*2 as test1 from [database].[dbo].table1 a ,[database].[dbo].table2 b where a.UserID = b.UserID and a.WorkAreaID = '2' group by b.UserName;


second query is:
SQL
select b.UserName as USER_NAME,sum(a.TotalCount) as test2 from [database] .[dbo].table3 a, [database].[dbo].table4 b where a.scope = 'Scrolling' and a.resources = b.UserName group by b.UserName;


and i want output like this
SQL
UserName   test1   test2
zzz        1000    2000
xxx        555     289


but if i run above query i am getting separate results/
Please help me on this

thanks
Posted
Updated 30-Mar-15 0:27am
v2

1 solution

A simple left/inner join can help
Try this-
SQL
select t1.USER_NAME as UserName, test1, test2
from
(
    select b.UserName as USER_NAME, sum(a.TotalCount)*2 as test1 from [database].[dbo].table1 a ,[database].[dbo].table2 b where a.UserID = b.UserID and a.WorkAreaID = '2' group by b.UserName
) as t1
left join
(
    select b.UserName as USER_NAME,sum(a.TotalCount) as test2 from [database] .[dbo].table3 a, [database].[dbo].table4 b where a.scope = 'Scrolling' and a.resources = b.UserName group by b.UserName
) as t2 on t1.USER_NAME=t2.USER_NAME

Hope, it helps :)
 
Share this answer
 
Comments
SukirtiShetty 1-Apr-15 7:25am    
it displays results for test1 but for test2 it shows null values.
Please help me on this
Suvendu Shekhar Giri 1-Apr-15 7:36am    
Make sure that `UserName` in `table2` are same as that in `table4`.
Or. you can try `full join`.
SukirtiShetty 2-Apr-15 0:34am    
UserName is same in both tables. i tried for full join also
Suvendu Shekhar Giri 2-Apr-15 0:53am    
Ok. Can you share the first 2-3 rows of data for each table? That can only help in this regard I guess.
SukirtiShetty 2-Apr-15 1:58am    
thank you it worked fine now i have changed the table3 data.
now its working fine as required.
thanks again for your help

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900