简体   繁体   English

分组时避免多个子选择

[英]Avoiding multiple sub-selects when grouping

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.分组意味着我需要一个子选择来访问表二中的 foo。 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.数据库是 DB2。

EDIT: join is many to one, ie think of table_one as orders and table_b as containing information for the item.编辑:join 是多对一的,即将 table_one 视为订单,将 table_b 视为包含该项目的信息。

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 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
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM