我有 2 個表,一個包含訂單資訊,一個包含訂單事件資訊,示例結構如下:
訂單表:
| 商戶ID | 訂單編號 | 數量 | 訂購日期 |
|---|---|---|---|
| 111111 | 123456 | 100 | 2021-07-01 |
| 111111 | 789012 | 50 | 2021-07-20 |
| 111111 | 642443 | 75 | 2021-08-12 |
事件表:
| 商戶ID | 訂單編號 | 事件 | 數量 | 日期 |
|---|---|---|---|---|
| 111111 | 789012 | 到期 | 50 | 2021-08-03 |
| 111111 | 642443 | 到期 | 75 | 2021-08-28 |
期望輸出:
我正在嘗試按商家 ID 和月份進行細分:
- 訂單數
- 訂單金額
- Expiry Count (無論過期日期如何,當月下的訂單有多少已過期)
- 到期總和(上述到期計數的值)
示例輸出:
| 商戶ID | 訂單_月 | 訂單數 | 訂單總和 | expiry_count | expiry_sum |
|---|---|---|---|---|---|
| 111111 | 7 | 3 | 150 | 1 | 50 |
| 111111 | 8 | 1 | 75 | 1 | 50 |
我嘗試了一些沒有運氣的查詢,我得到的最遠的是:
select o.merchant_id, extract(month from o.order_date) as order_month, count(o.order_id) as order_count, sum(o.order_amount) as order_sum, count(e.order_id) as expiry_count, sum(e.amount) as expiry_sum
from orders o
left join events e on e.order_id = o.order_id
where o.merchant_id = '111111'
and o.order_date >= '2021-07-01'
group by o.merchant_id, order_month
order by o.merchant_id, order_month
但是,它輸出的 order_count 和 expiry_count 以及 order_sum 和 expiry_sum 的值完全相同。此外,我只需要檢索事件,event = 'EXPIRY'但是當我添加該過濾器時我沒有得到任何結果。
任何幫助將非常感激!
uj5u.com熱心網友回復:
如果我正確閱讀了您的問題……
將條件添加event到連接(不是 where):
select o.merchant_id, extract(month from o.order_date) as order_month, count(o.order_id) as order_count, sum(o.order_amount) as order_sum, count(e.order_id) as expiry_count, sum(e.amount) as expiry_sum
from orders o
left join events e on e.order_id = o.order_id
and e.event = 'EXPIRY'
where o.merchant_id = '111111'
and o.order_date >= '2021-07-01'
group by o.merchant_id, order_month
order by o.merchant_id, order_month
如果將外部聯接表上的條件置于where子句中,則會強制聯接表現為內部聯接(就像洗掉left關鍵字一樣)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359850.html
標籤:sql PostgreSQL的
