Rank() SQL 或类似的东西
Rank() SQL Or Something like that
你好,有什么方法可以获得这些账户余额,就像我想计算贷方和借方一样
1 - 1000
2 - 1000-500 = 500
3 - 500-700 = -200
依此类推取决于日期
有什么解决办法比如rank之类的可以帮忙吗?
太感谢了/
使用LAG
解析函数:
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
其中,对于示例数据:
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;
输出:
Date
CREDIT
DEBIT
ACCOUNT_BALANCE
01-JAN-21
1000
0
1000
02-JAN-21
0
500
500
03-JAN-21
0
700
-200
反方向计算:
SELECT "Date",
credit,
debit,
SUM(credit-debit) OVER (ORDER BY "Date") AS account_balance
FROM table_name
其中,对于示例数据:
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;
输出:
Date
CREDIT
DEBIT
ACCOUNT_BALANCE
01-JAN-21
1000
0
1000
02-JAN-21
0
500
500
03-JAN-21
0
700
-200
db<>fiddle here
你好,有什么方法可以获得这些账户余额,就像我想计算贷方和借方一样
1 - 1000
2 - 1000-500 = 500
3 - 500-700 = -200
依此类推取决于日期
有什么解决办法比如rank之类的可以帮忙吗? 太感谢了/
使用LAG
解析函数:
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
其中,对于示例数据:
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;
输出:
Date CREDIT DEBIT ACCOUNT_BALANCE 01-JAN-21 1000 0 1000 02-JAN-21 0 500 500 03-JAN-21 0 700 -200
反方向计算:
SELECT "Date",
credit,
debit,
SUM(credit-debit) OVER (ORDER BY "Date") AS account_balance
FROM table_name
其中,对于示例数据:
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;
输出:
Date CREDIT DEBIT ACCOUNT_BALANCE 01-JAN-21 1000 0 1000 02-JAN-21 0 500 500 03-JAN-21 0 700 -200
db<>fiddle here