Oracle
 sql >> Teknologi Basis Data >  >> RDS >> Oracle

Pertanyaan wawancara:Bagaimana cara mendapatkan agregasi 3 bulan terakhir di tingkat kolom?

Pertama-tama Anda perlu menjumlahkan data bulan lalu menggunakan fungsi LAG untuk mendapatkan data bulan sebelumnya sebagai berikut:

SELECT
    ORDER_MONTH,
    LAG(UNIT_OF_PHONE_SALE, 1) OVER(
        ORDER BY
            ORDER_MONTH
    ) AS "M-1_Sale",
    LAG(UNIT_OF_PHONE_SALE, 2) OVER(
        ORDER BY
            ORDER_MONTH
    ) AS "M-2_Sale",
    LAG(UNIT_OF_PHONE_SALE, 3) OVER(
        ORDER BY
            ORDER_MONTH
    ) AS "M-3_Sale"
FROM
    (
        SELECT
            TO_CHAR(ORDERDATE, 'YYYYMM') AS ORDER_MONTH,
            SUM(UNIT_OF_PHONE_SALE) AS UNIT_OF_PHONE_SALE
        FROM
            DATAA
        GROUP BY
            TO_CHAR(ORDERDATE, 'YYYYMM')
    )
ORDER BY
    ORDER_MONTH DESC;

Keluaran:

ORDER_   M-1_Sale   M-2_Sale   M-3_Sale
------ ---------- ---------- ----------
201908       3789        789        666
201907        789        666        765
201906        666        765
201905        765
201904

db<>demo biola

Semangat!!

-- Perbarui --

Untuk persyaratan yang disebutkan dalam komentar, Kueri berikut akan berfungsi untuk itu.

CTE AS (
    SELECT
        TRUNC(ORDERDATE, 'MONTH') AS ORDER_MONTH,
        SUM(UNIT_OF_PHONE_SALE) AS UNIT_OF_PHONE_SALE
    FROM
        DATAA
    GROUP BY
        TRUNC(ORDERDATE, 'MONTH')
)

SELECT
    TO_CHAR(C.ORDER_MONTH,'YYYYMM') as ORDER_MONTH,
    NVL(C1.UNIT_OF_PHONE_SALE, 0) AS "M-1_Sale",
    NVL(C2.UNIT_OF_PHONE_SALE, 0) AS "M-2_Sale",
    NVL(C3.UNIT_OF_PHONE_SALE, 0) AS "M-3_Sale"
FROM
    CTE C
    LEFT JOIN CTE C1 ON ( C1.ORDER_MONTH = ADD_MONTHS(C.ORDER_MONTH, - 1) )
    LEFT JOIN CTE C2 ON ( C2.ORDER_MONTH = ADD_MONTHS(C.ORDER_MONTH, - 2) )
    LEFT JOIN CTE C3 ON ( C3.ORDER_MONTH = ADD_MONTHS(C.ORDER_MONTH, - 3) )
ORDER BY
    C.ORDER_MONTH DESC

Keluaran:

db<>demo biola dari jawaban yang diperbarui.

Semangat!!



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Apakah ada antarmuka .Net untuk Oracle SQLPLUS?

  2. Baca Dan Impor File CSV Di Oracle PL/SQL Secara Efisien

  3. Apa perbedaan antara setTime(...) dan setTimestamp(...) di Hibernate Query?

  4. Tidak dapat membuat driver dari NHibernate.Driver.OracleDataClientDriver

  5. Maks dari jumlah kueri