sql >> Database teknologi >  >> RDS >> Oracle

Rank() SQL eller sådan noget

Brug LAG analytisk funktion:

SELECT "Date",
       GREATEST(
         account_balance - LAG(account_balance, 1, 0) OVER (ORDER BY "Date"),
         0
       ) AS credit,
       GREATEST(
         LAG(account_balance, 1, 0) OVER (ORDER BY "Date") - account_balance,
         0
       ) AS debit,
       account_balance
FROM   table_name

Hvilket, for eksempeldata:

CREATE TABLE table_name ( "Date", account_balance ) AS
SELECT Date '2021-01-01', +1000 FROM DUAL UNION ALL
SELECT Date '2021-01-02', + 500 FROM DUAL UNION ALL
SELECT Date '2021-01-03', - 200 FROM DUAL;

Udgange:

For at beregne i den modsatte retning:

SELECT "Date",
       credit,
       debit,
       SUM(credit-debit) OVER (ORDER BY "Date") AS account_balance
FROM   table_name

Hvilket, for eksempeldata:

CREATE TABLE table_name ( "Date", credit, debit ) AS
SELECT Date '2021-01-01', 1000,   0 FROM DUAL UNION ALL
SELECT Date '2021-01-02',    0, 500 FROM DUAL UNION ALL
SELECT Date '2021-01-03',    0, 700 FROM DUAL;

Udgange:

db<>fiddle her




  1. Django forespørgselsudtryk for beregnede felter, der kræver betingelser og casting

  2. Er der en MySQL kommando drop alle indekser undtagen PRIMÆR indeks?

  3. Hvordan opretter man en kompleks virtuel kolonne i en veltalende model?

  4. MySQL STR_TO_DATE NULL ved fejl