有什么办法可以避免笛卡尔加入 sql plus

Is there any way to avoid cartesian join in sql plus

我有下面给出的三个 table:

supplied_items(SUPPLIER_ID,ITEM_ID,QUANTITY,COST_PRICE);
ORDERS(ORDER_ID,CUSTOMER_ID,EMPLOYEE_ID,ITEM_ID,PRICE,QUANTITY,TOTAL_PRICE,ODATE);
EXPENSES(EXPENSE_ID,EDATE,DESCRIPTION,PAYMENT_TYPE,AMOUNT);

我必须计算净利润。但是当我在查询中包含费用 table 时,它会与其他 table 的行生成笛卡尔积。 以下是我的查询:

SELECT
    SUM(orders.quantity * orders.price) AS "Sale",
    SUM(orders.quantity * supplied_items.cost_price) AS "COST",
    SUM(orders.quantity *(orders.price - supplied_items.cost_price)) AS "Profit",
    SUM(expenses.amount)
FROM
    orders
    LEFT OUTER JOIN supplied_items ON orders.item_id = supplied_items.item_id
    CROSS JOIN expenses;                                    

看来你需要费用的全部结果table:

SELECT
    SUM(orders.quantity * orders.price) AS "Sale",
    SUM(orders.quantity * supplied_items.cost_price) AS "COST",
    SUM(orders.quantity *(orders.price - supplied_items.cost_price)) AS "Profit",
    MAX(select SUM(expenses.amount) from expenses) as "Expenses"
FROM
    orders
    LEFT OUTER JOIN supplied_items ON orders.item_id = supplied_items.item_id

ORA-00937: not a single-group group function Cause:

A SELECT list cannot include both a group function, such as AVG, COUNT, MAX, MIN, SUM, STDDEV, or VARIANCE, and an individual column expression, unless the individual column expression is included in a GROUP BY clause.

这意味着如果不使用正确的 group by 子句,您就不能在 oracle 中将聚合函数与没有聚合的列一起使用。

出于同样的原因,您不能使用 select a,sum(b) from table1select sum(b),(select sum(a)from able1)from table1

您需要像其他列一样用组函数包装子查询。请试试这个:

SELECT
    SUM(orders.quantity * orders.price) AS "Sale",
    SUM(orders.quantity * supplied_items.cost_price) AS "COST",
    SUM(orders.quantity *(orders.price - supplied_items.cost_price)) AS "Profit",
    max(select SUM(expenses.amount) from expenses) expense_amount
FROM
    orders
    LEFT OUTER JOIN supplied_items ON orders.item_id = supplied_items.item_id;   

或者您也可以这样做:

select Sale, COST, Profit,(select SUM(expenses.amount) from expenses) expense_amount
from
(SELECT
    SUM(orders.quantity * orders.price) AS "Sale",
    SUM(orders.quantity * supplied_items.cost_price) AS "COST",
    SUM(orders.quantity *(orders.price - supplied_items.cost_price)) AS "Profit",
    
FROM
    orders
    LEFT OUTER JOIN supplied_items ON orders.item_id = supplied_items.item_id;   
)t