分组时避免多个子选择

时间:2009-04-20 08:46:37

标签: sql db2

我的查询类似于:

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

分组意味着我需要一个子选择来访问表2中的foo。现在,如果我想从表2中选择第二列,有没有办法在没有第二个子选择的情况下访问它?

数据库是DB2。

编辑: join是多对一的,即将table_one视为orders,将table_b视为包含该项的信息。

2 个答案:

答案 0 :(得分:2)

table_two是否为每个table_one.x有多行,或者它是一对一的连接... 如果它是一对二,那么这不会做你想要的...因为你的子选择是在与你的连接相同的条件下完成的

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

答案 1 :(得分:0)

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