Oracle SQL不是按表达式分组

时间:2018-12-14 08:20:54

标签: sql oracle

当我运行这段代码

SELECT sales_date AS DAY, SUM (TOTAL_AMOUNT_RM) 

FROM SALESINVOICE

GROUP BY SALES_DATE

order by sales_date;

它给了我一张桌子 enter image description here

然后我运行其他代码

SELECT SR.DAY, SUM(SR.PROFIT_RM) AS TOTALPROFIT_RM

FROM

(SELECT SALESINVOICE_ID AS NO, S.ITEM_ID AS ITEM, SALES_DATE AS DAY, S.QUANTITY, C.PRICE_RM, C.COST_RM, ((S.QUANTITY*C.PRICE_RM)-(S.QUANTITY*C.COST_RM)) AS PROFIT_RM

FROM SALESINVOICE S

INNER JOIN (SELECT ITEM_ID, PRICE_RM, COST_RM FROM ITEM I ) C

ON S.ITEM_ID = C.ITEM_ID
ORDER BY SALESINVOICE_ID, SALES_DATE) SR 
GROUP BY SR.DAY

ORDER BY SR.DAY;

给了我一张桌子enter image description here

我尝试内部连接两个表,但是当我尝试调用列sum(total_amount_rm)时,它给了我一个表达式错误分组

SELECT SR.DAY, SUM(SR.PROFIT_RM) AS TOTALPROFIT_RM, D.TOTAL

FROM 

(SELECT SALESINVOICE_ID AS NO, S.ITEM_ID AS ITEM, SALES_DATE AS DAY, S.QUANTITY, C.PRICE_RM, C.COST_RM, ((S.QUANTITY*C.PRICE_RM)-(S.QUANTITY*C.COST_RM)) AS PROFIT_RM

FROM SALESINVOICE S

INNER JOIN (SELECT ITEM_ID, PRICE_RM, COST_RM FROM ITEM I ) C
ON S.ITEM_ID = C.ITEM_ID
ORDER BY SALESINVOICE_ID, SALES_DATE) SR

INNER JOIN (SELECT SALES_DATE AS DAY, SUM(TOTAL_AMOUNT_RM) AS TOTAL FROM SALESINVOICE GROUP BY SALES_DATE ORDER BY SALES_DATE) D

ON D.DAY = SR.DAY

GROUP BY SR.DAY

ORDER BY SR.DAY;

但是,它可以在不选择D.TOTAL的情况下运行。谁能帮我?我是sql新手

1 个答案:

答案 0 :(得分:0)

由于GROUP BY子句中SELECT子句中所有不在GROUP BY子句中的列都必须带有聚合函数,因此会出现错误

要解决此问题,一种方法是在加入之前计算总和

SELECT s.day, s.totalprofit_rm, d.total
FROM 
(
    SELECT sr.day, 
        SUM(sr.profit_rm) AS totalprofit_rm
    FROM
    (
        SELECT salesinvoice_id AS no, 
            s.item_id AS item, 
            sales_date AS day, 
            s.quantity, 
            c.price_rm, 
            c.cost_rm, 
            (s.quantity * c.price_rm) - (s.quantity * c.cost_rm) AS profit_rm
        FROM salesinvoice s
        INNER JOIN (SELECT item_id, price_rm, cost_rm FROM item) c
        ON s.item_id = c.item_id
    ) sr
    GROUP BY sr.day
) s
INNER JOIN 
(
    SELECT sales_date AS day, 
        SUM(total_amount_rm) AS total 
    FROM salesinvoice 
    GROUP BY sales_date
) d
ON d.day = s.day
ORDER BY s.day;

上述查询可以更短一些:

SELECT sr.day, sr.totalprofit_rm, d.total
FROM 
(
    SELECT 
        s.sales_date AS day, 
        SUM((s.quantity * c.price_rm) - (s.quantity * c.cost_rm)) AS totalprofit_rm
    FROM salesinvoice s
    INNER JOIN item c
    ON s.item_id = c.item_id
    GROUP BY s.sales_date  
) sr
INNER JOIN 
(
    SELECT sales_date AS day, 
        SUM(total_amount_rm) AS total 
    FROM salesinvoice 
    GROUP BY sales_date
) d
ON d.day = sr.day
ORDER BY sr.day;