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
 SQL Server 2005 Forums
 Other SQL Server Topics (2005)
 Joining results from two tables with no Unique col

Author  Topic 

SQL_Nid
Starting Member

2 Posts

Posted - 2013-06-06 : 08:03:35
I have two tables with no common columns:
Graph_Range Start_Range End_Range
0.10 0.20
0.20 0.30
0.30 0.40



Graph_data
Asset_Value factor Case
500 0.12 1
270 0.13 2
300 0.27 3
240 0.23 4
200 0.13 5
100 0.12 6


I need results as Lower Limit Upper Limit Sum_Asset
0.10 0.20 1,070
0.20 0.30 540
0.30 0.40 -

i.e. it should give sum of asset values in case the relevant factor falls between start and end range.

I am not sure how can I get results in such data set as UNION, CROSS JOIN,INNER JOIN are not working. Either I am getting repaeted entires or error messages. Please help.
I have used this query
SELECT A.Start_Range, A.End_Range, SUM(B.asset) AS Sum_Asset
FROM dbo.Graph_Range AS A , dbo.Graph_Data AS B
GROUP BY A.Start_Range, A.End_Range , b.Factor
HAVING (B.Factor < A.End_Range) AND (B.Factor > A.Start_Range)

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2013-06-06 : 09:52:26
[code]--I have two tables with no common columns:
declare @Graph_Range table (Start_Range decimal(3,2), End_Range decimal(3,2))
insert @Graph_Range
select 0.10, 0.20 union all
select 0.20, 0.30 union all
select 0.30, 0.40

declare @Graph_data table (Asset int, factor decimal(3,2), [case] int)
insert @Graph_data
select 500, 0.12, 1 union all
select 270, 0.13, 2 union all
select 300, 0.27, 3 union all
select 240, 0.23, 4 union all
select 200, 0.13, 5 union all
select 100, 0.12, 6


--I need results as Lower Limit Upper Limit Sum_Asset
--0.10 0.20 1,070
--0.20 0.30 540
--0.30 0.40 -

--i.e. it should give sum of asset values in case the relevant factor falls between start and end range.
select
Start_Range,
End_Range,
SUM(Asset) as Sum_Asset
from
(
SELECT
A.Start_Range,
A.End_Range,
B.Factor,
B.Asset
FROM @Graph_Range AS A
LEFT JOIN @Graph_Data AS B ON B.Factor between A.Start_Range and A.End_Range
)dt
GROUP BY Start_Range, End_Range
[/code]


Too old to Rock'n'Roll too young to die.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-06-07 : 02:13:27
[code]
SELECT g.Start_Range AS Lower_Limit,
g.End_Range AS Upper_limit,
COALESCE(d.SumAsset,0) AS Sum_Asset
FROM Graph_Range g
OUTER APPLY (SELECT SUM(Asset) AS Sum_Asset
FROM Graph_data
WHERE factor BETWEEN g.Start_Range AND g.End_Range
)d
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -