oracle PLSQL按组计算

kmpatx3s  于 2023-04-20  发布在  Oracle
关注(0)|答案(2)|浏览(166)

我有一个表,其中包含所有供应商的每个订单。我有以下查询,计算按不同日期参数筛选的每个供应商的总订购量。

SELECT 
    (
        SELECT SUM(ORDER_QTY)
        FROM  MY_TABLE
        WHERE  DELIVERY_DATE BETWEEN TRUNC(SYSDATE, 'YEAR') AND TRUNC(SYSDATE)
    ) AS YTD,
    (
        SELECT SUM(ORDERQTY)
        FROM   MY_TABLE
        WHERE  STATE = 'CONFIRMED'
        OR     STATE = 'RELEASED'
        AND    DELIVERY_DATE >= SYSDATE
    ) AS OVERDUE,
    SUPPLIER,
    SUPPLIER_NO 
FROM MY_TABLE 
GROUP  BY SUPPLIER

查询返回所有供应商的总和(即每行中的相同数字),而不是每个供应商的单个总和。我是PLSQL的新手,不知道我哪里出错了。

y1aodyip

y1aodyip1#

代码中的一个问题是子查询与外部查询不相关(通常,应该有一个供应商编号过滤器)。此外,在其中一个WHERE子句中混合了ANDOR,这可能并不符合您的要求。
根据你的问题陈述,我认为你不需要子查询,而是需要条件聚合。类似于:

SELECT SUPPLIER_NO, SUPPLIER,
    SUM(
        CASE
            WHEN DELIVERY_DATE BETWEEN TRUNC(SYSDATE, 'YEAR') AND TRUNC(SYSDATE) 
            THEN ORDER_QTY 
            ELSE 0 
        END
    ) as YTD,
    SUM(
        CASE 
            WHEN STATE IN ('CONFIRMED', 'RELEASED') AND DELIVERY_DATE >= SYSDATE 
            THEN ORDER_QTY 
            ELSE 0 
        END
    ) as OVERDUE
FROM MY_TABLE
GROUP BY SUPPLIER_NO, SUPPLIER
4szc88ey

4szc88ey2#

我也更喜欢条件聚合方法更好(见GMB的回答),但这里有一个相关的查询方法:

SELECT 
    T1.SUPPLIER_NO,
    T1.SUPPLIER,
(SELECT 
    SUM(ORDER_QTY)
    FROM  MY_TABLE T2 
    WHERE  
        T2.SUPPLIER_NO = T1.SUPPLIER_NO
        AND DELIVERY_DATE BETWEEN TRUNC(SYSDATE, 'YEAR') AND TRUNC(SYSDATE)) AS YTD,
(SELECT 
    SUM(ORDERQTY)
    FROM MY_TABLE T3
    WHERE  
        T3.SUPPLIER_NO = T1.SUPPLIER_NO
        AND (STATE = 'CONFIRMED' OR STATE = 'RELEASED')
        AND    DELIVERY_DATE >= SYSDATE) AS OVERDUE,
FROM 
    MY_TABLE T1

相关问题