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

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Basic join or select question

Author  Topic 

romeck
Starting Member

16 Posts

Posted - 2012-11-12 : 17:15:13
i have 2 tables like this
X {id, value1}
Y{id,idx,value2}

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 y.idx=x.id), 4) 2)-3)

which query is faster ?

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

THQ

Bustaz Kool
Master Smack Fu Yak Hacker

1834 Posts

Posted - 2012-11-12 : 19:55:13
[CODE]select x.id, x.value1, sum(y.value2), x.value1 - sum(y.value2)
from x
inner join y
on x.id = y.idx
group by
x.id, x.value1[/CODE]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

romeck
Starting Member

16 Posts

Posted - 2012-11-19 : 15:42:04
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

sodeep
Master Smack Fu Yak Hacker

7174 Posts

Posted - 2012-11-19 : 15:54:58
You mean this one:

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

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-11-20 : 01:50:26
[code]
SELECT m.id,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
)n
ON n.idx = m.id

[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -