Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Basic join or select question
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

16 Posts

Posted - 11/12/2012 :  17:15:13  Show Profile  Reply with Quote
i have 2 tables like this
X {id, value1}

X data
1 1500
2 400
3 100
4 1000
5 400

Y data
1 1 200
2 1 400
3 3 100
4 2 100

How should i make join query that return
1 1500 600 900
2 400 100 300
3 100 100 0
4 1000 0 1000
5 400 0 400

Which basicaly is
1) x.idx, 2)x.value, 3)sum(value2 from y where, 4) 2)-3)

which query is faster ?

select id ,value , select(sum(value2) from y where as sums, value - sums from x
or the join query i ask you to create.


Bustaz Kool
Flowing Fount of Yak Knowledge

1834 Posts

Posted - 11/12/2012 :  19:55:13  Show Profile  Reply with Quote
select, x.value1, sum(y.value2), x.value1 - sum(y.value2)
from x
inner join y
  on = y.idx
group by, x.value1
Having the subquery in the SELECT caluse, as you have done it, would probably have the subquery execute for every record returned and therefore would be slower. The SQL Engine might be smart enough to figure out what you have done and fix things under the covers but it might not.

We are far more concerned about the desecration of the flag than we are about the desecration of our land. -Wendell Berry
Go to Top of Page

Starting Member

16 Posts

Posted - 11/19/2012 :  15:42:04  Show Profile  Reply with Quote
but as i use inner join then in output i do not have line 4 coouse it do not have any records in Y table. and i neeed to have all records from table X despite of any records for it in Y.
Go to Top of Page

Flowing Fount of Yak Knowledge

7174 Posts

Posted - 11/19/2012 :  15:54:58  Show Profile  Reply with Quote
You mean this one:

Select,x.Value1,YSUM,ISNULL(Value1,0) - YSUM
from x
inner join
from x
left join y on = y.idx
group by
)y on =
Go to Top of Page

Very Important crosS Applying yaK Herder

52326 Posts

Posted - 11/20/2012 :  01:50:26  Show Profile  Reply with Quote

SELECT,m.value1,COALESCE(n.Tot,0) AS Tot,m.value1-COALESCE(n.Tot,0) AS Res
FROM x m
LEFT JOIN (SELECT idx,SUM(value2) AS Tot
           FROM y
           GROUP BY idx
ON n.idx =

SQL Server MVP

Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000