如何将查询转换为嵌套查询

时间:2019-09-30 06:06:47

标签: sql sqlite subquery

如何将此查询更改为嵌套查询? 查询和表在下面列出。

SELECT 
  Nation.N_NAME as "nation", 
  ROUND(
    SUM(
      Lineitem.L_QUANTITY * (Lineitem.L_EXTENDEDPRICE - Lineitem.L_DISCOUNT)
    ), 2
  ) AS "order size"
FROM Nation
JOIN Supplier ON Nation.N_NATIONKEY = Supplier.S_NATIONKEY
JOIN Customer ON Supplier.S_NATIONKEY = Customer.C_NATIONKEY
JOIN Orders ON Customer.C_CUSTKEY = Orders.O_CUSTKEY
JOIN Lineitem ON Orders.O_ORDERKEY = Lineitem.L_ORDERKEY
WHERE Lineitem.L_SUPPKEY = Supplier.S_SUPPKEY
GROUP BY Nation.N_NAME
;

表如下

国家:N_NATIONKEY,N_NAME

供应商:S_SUPPKEY,S_NAME,S_NATIONKEY

客户:C_CUSTKEY,C_NAME,C_NATIONKEY

订单:O_ORDERKEY,O_CUSTKEY

订单项:L_ORDERKEY,L_SUPPKEY,L_QUANTITY,L_EXTENDEDPRICE,L_DISCOUNT

1 个答案:

答案 0 :(得分:0)

我不确定您要寻找哪种nested join,但是这里有一个选择:

SELECT
  src.N_NAME as "nation", 
  ROUND(
    SUM(
      lineitem.L_QUANTITY * (lineitem.L_EXTENDEDPRICE - lineitem.L_DISCOUNT)
    ), 2
  ) AS "order size"
FROM lineitem -- Get line items
INNER JOIN (
  SELECT nation.N_NAME, supplier.S_SUPPKEY, Orders.O_ORDERKEY
  FROM nation
  JOIN Supplier ON Nation.N_NATIONKEY = Supplier.S_NATIONKEY
  JOIN Customer ON Supplier.S_NATIONKEY = Customer.C_NATIONKEY
  JOIN Orders ON Customer.C_CUSTKEY = Orders.O_CUSTKEY
) src ON lineitem.L_SUPPKEY = src.S_SUPPKEY AND lineitem.L_ORDERKEY = src.O_ORDERKEY
GROUP BY src.N_NAME

我还没有测试过,但是尝试一下,看看它是否有效。如果它不能满足您的需求,请发布一些示例数据。