tags:

views:

223

answers:

2

I have a query that works like:

select table_one.x, sum(table_one.y)
(select foo from table_two where table_one.x = table_two.x) as item_description
from table_one
inner join table_two
on table_one.x = table_two.x
-- where table_2 row has various attributes
group by table_one.x

The grouping means I need a sub-select to access foo from table two. Now if I want to select a second column from table two, is there any way to access this without a second sub-select?

Database is DB2.

EDIT: join is many to one, ie think of table_one as orders and table_b as containing information for the item.

+2  A: 

does table_two have multiple rows for each table_one.x or is it a one-2-one join... if it's one-2-one then does this not do what you want... since your sub-select is done on the same conditions as your join

SELECT
   table_one.x, table_two.foo, sum(table_one.y)
FROM table_one
   INNER JOIN table_two
       ON table_one.x = table_two.x 
GROUP BY
   table_one.x, table_two.foo
Eoin Campbell
A: 
SELECT  *
FROM    (
        SELECT  x, SUM(y)
        FROM    table_one
        GROUP BY
                x
        ) AS t1
INNER JOIN
        table_two t2
ON      t2.x = t1.x
-- where table_2 row has various attributes
Quassnoi
the performance may not be good for this as it materializes t1 first before joining t2
kishore
I don't know DB2 in depth, but Oracle and MS SQL don't materialize the whole view provided there's an index on table_one(x).
Quassnoi