我嘗試在 SQL (Oracle) 中撰寫一個查詢,結果將在列中 count
我使用分析函式count(*),但結果是錯誤的。
我想得到像列數一樣的結果。如果列付款為 0 或 null,則列計數被重置。否則將列計數中的值加一
我想獲得的帶有輸出的表(targetcolumns --> counts)TARGET TABLE
| 日期 | ID | 支付 | 計數 |
|---|---|---|---|
| 20210131 | 111111111 | 0 | 0 |
| 20210228 | 111111111 | 0 | 0 |
| 20210331 | 111111111 | 0 | 0 |
| 20210430 | 111111111 | 100 | 1 |
| 20210531 | 111111111 | 200 | 2 |
| 20210630 | 111111111 | 400 | 3 |
| 20210731 | 111111111 | 0 | 0 |
| 20210830 | 111111111 | 0 | 0 |
| 20210930 | 111111111 | 0 | 0 |
| 20211031 | 111111111 | 200 | 1 |
| 20211130 | 111111111 | 500 | 2 |
| 20211231 | 111111111 | 0 | 0 |
寫完這段代碼后,我得到了這個結果。
select
date, id, payment,
count(payment) over (partition by id order by date) as counts
from
table
這是我現在得到的錯誤結果:
| 日期 | ID | 支付 | 計數 |
|---|---|---|---|
| 20210131 | 111111111 | 0 | 0 |
| 20210228 | 111111111 | 0 | 0 |
| 20210331 | 111111111 | 0 | 0 |
| 20210430 | 111111111 | 100 | 1 |
| 20210531 | 111111111 | 200 | 2 |
| 20210630 | 111111111 | 400 | 3 |
| 20210731 | 111111111 | 0 | 3 |
| 20210830 | 111111111 | 0 | 3 |
| 20210930 | 111111111 | 0 | 3 |
| 20211031 | 111111111 | 200 | 4 |
| 20211130 | 111111111 | 500 | 5 |
| 20211231 | 111111111 | 0 | 5 |
uj5u.com熱心網友回復:
因此,您似乎想計算付款不為零的行?如果是這種情況,您可以這樣做(使用您的查詢):
select
date, id, payment,
sum(case when payment = 0 then 0 else 1 end) over (partition by id order by date) as counts
from table
并且不要使用保留字(如日期)命名列,它可以做到但一個非常糟糕的習慣。
uj5u.com熱心網友回復:
樣本資料:
SQL> select * from test order by datum;
DATUM ID PAYMENT
---------- ---------- ----------
20210131 1 0
20210228 1 0
20210331 1 0
20210430 1 100
20210531 1 200
20210630 1 400
20210731 1 0
20210830 1 0
20210930 1 0
20211031 1 200
20211130 1 500
20211231 1 0
12 rows selected.
回傳您期望的結果的查詢:
GRPCTE:根據每組payment中的列值確定行id組(我想可能還有其他)- final
select:使用case運算式將結果設定為0ifpayment = 0;否則,使用row_number決議函式
SQL> with grp as
2 (select datum, id, payment,
3 sum(case payment when 0 then 1 else 0 end) over (partition by id order by datum) grp
4 from test
5 )
6 select datum, id, payment,
7 case when payment = 0 then 0
8 else row_number() over (partition by id, grp order by datum) - 1
9 end rn
10 from grp
11 order by datum;
DATUM ID PAYMENT RN
---------- ---------- ---------- ----------
20210131 1 0 0
20210228 1 0 0
20210331 1 0 0
20210430 1 100 1
20210531 1 200 2
20210630 1 400 3
20210731 1 0 0
20210830 1 0 0
20210930 1 0 0
20211031 1 200 1
20211130 1 500 2
20211231 1 0 0
12 rows selected.
SQL>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/417784.html
標籤:
