如何按一定時期計算付款。
具體來說,我想知道用戶是否在 x 日期注冊,從該日期起 30 天內他有多少付款
有兩個表:
create table user (user_id, contact, registration_date) as
select 1, 111 111, 1/18/2022 3:57:32 PM from dual union all
select 2, 222 222, 8/12/2021 12:00:12 AM from dual union all
select 3, 333 333, 12/11/2015 5:08:35 PM from dual union all
select 4, 444 444, 5/25/2020 10:59:10 AM from dual;
create table transaction (day, user_id, payment) as
select 1/20/2022, 1, 5 from dual union all
select 1/30/2022, 1, 8 from dual union all
select 2/20/2022, 1, 6 from dual union all
select 8/12/2021 , 2, 10 from dual union all
select 8/15/2021 , 2, 5 from dual union all
select 9/25/2021 , 2, 12 from dual union all
select 12/11/2015 , 3, 18 from dual union all
select 12/20/2015 , 3, 10 from dual union all
select 1/1/2016 , 3, 10 from dual union all
select 5/26/2020 , 4, 7 from dual union all
select 6/1/2020 , 4, 2 from dual;
我想知道這樣的事情,但是這個查詢不起作用,
select t.user_id,u.registration_date,sum(t.payment) from transaction t
left join user u on t.user_id = u.user_id
where t.day >= u.registration_date and t.day <= u.registration_date interval '30' days
group by t.user_id
我的預期表:
| 用戶身份 | 登記日期 | 支付 |
|---|---|---|
| 1 | 2022 年 1 月 18 日下午 3:57:32 | 13 |
| 2 | 2021 年 8 月 12 日上午 12:00:12 | 15 |
| 3 | 2015 年 12 月 11 日下午 5:08:35 | 38 |
| 4 | 2020 年 5 月 25 日上午 10:59:10 | 9 |
uj5u.com熱心網友回復:
首先,您可能希望將交易外部連接到用戶,反之亦然。因此,您還可以顯示注冊后 30 天內沒有交易的用戶。
然后,Oracle 要求您u.registration_date輸入GROUP BY或偽聚合它(例如MIN(u.registration_date))。這不符合標準 SQL,但似乎 Oracle 還沒有設法正確檢測功能依賴關系,因此他們根本不提供此功能。
最后,注冊日期,盡管它的名字,不是一個日期,而是一個日期時間。為了將其與交易日期進行比較,請將其截斷。然后決定是否要包括注冊日期后的第 30 天(即添加 30 或 31 天并使用 < 無論如何)。
select u.user_id, u.registration_date, sum(t.payment)
from users u
left join transactions t
on t.user_id = u.user_id
and t.day >= trunc(u.registration_date)
and t.day < trunc(u.registration_date) interval '31' day
group by u.user_id, u.registration_date
order by u.user_id;
演示:https ://dbfiddle.uk/?rdbms=oracle_21&fiddle=a6d8d13c994eff6a1c0f8afa6fcb176f
uj5u.com熱心網友回復:
好像
SQL> SELECT u.user_id, u.registration_date, SUM (t.payment) payment
2 FROM tuser u JOIN transaction t ON t.user_id = t.user_id
3 WHERE t.day BETWEEN u.registration_date
4 AND u.registration_date INTERVAL '30' DAY
5 GROUP BY u.user_id, u.registration_date
6 ORDER BY u.user_id;
USER_ID REGISTRATI PAYMENT
---------- ---------- ----------
1 01/18/2022 13
2 08/12/2021 15
3 12/11/2015 38
4 05/25/2020 9
SQL>
uj5u.com熱心網友回復:
您的查詢不起作用,因為您忘記在 GROUP BY 子句中添加 u.registration_date。當您執行 GROUP BY 時,SELECT 中提到的所有欄位都需要添加到 GROUP BY 或用于聚合函式,如 SUM、MIN、MAX、...
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/448736.html
上一篇:從XML檔案中提取值
