[英]Avoiding multiple sub-selects when grouping
我有一個查詢,其工作方式如下:
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
分組意味着我需要一個子選擇來訪問表二中的 foo。 現在,如果我想從表二中選擇第二列,有沒有辦法在沒有第二個子選擇的情況下訪問它?
數據庫是 DB2。
編輯:join 是多對一的,即將 table_one 視為訂單,將 table_b 視為包含該項目的信息。
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.