[英]Postgresql get List all customer who has 3 or more record transaction
我正在使用 postgreSQL。 我有 2 張關系表
表客戶:
-------------------------------------------
| customer_id (PK) | first_name | last_name |
-------------------------------------------
| 1 | ogi | tampoo |
| 2 | cimol | comet |
| 3 | cocang | tampoo |
| 4 | bedu | comet |
| 5 | bonjof | tampoo |
表事務:
---------------------------------------------------------
| transaction_id (PK) | customer_id (FK) | total_value |
---------------------------------------------------------
| 2 | 1 | 250500 |
| 5 | 2 | 340600 |
| 4 | 3 | 150800 |
| 6 | 4 | 90900 |
| 3 | 4 | 1009000 |
| 1 | 5 | 540700 |
| 7 | 4 | 340000 |
問題:
Return all customer who has >1 record transaction.
Obviously from transaction table, customer_id = 4 have 3 records
how to query this?
期望的結果
--------------------------------------------------------------------------------------
| customer_id | first_name | last_name | transaction_id | customer_id | total_value |
--------------------------------------------------------------------------------------
| 4 | bedu | comet | 5 | 4 | 90900 |
| 4 | bedu | comet | 3 | 4 | 1009000 |
| 4 | bedu | comet | 7 | 4 | 340000 |
我嘗試過的:
select cs.* ,tr.*
from
customer cs
left join
transaction tr
on tr.customer_id = cs.customer_id
group by cs.customer_id , tr.transaction_id
having count(cs.customer_id)>1
select *
from
customer cs
left join
transaction tr
on tr.customer_id = cs.customer_id
group by tr.customer_id
having count(tr.customer_id)>1
看來(我不知道它是否只有 postgres),它強制按每個 PRIMARY KEY 分組。
當我嘗試按任何其他不是 PK 的列進行分組時,它會返回錯誤並要求 PK 為group by 。
非常感謝。
您的最后一個查詢幾乎可以工作。 只需 select 客戶表中的列 - 並通過主鍵連接:
select c.*
from customer c join
transaction t
on t.customer_id = c.customer_id
group by c.customer_id
having count(*) > 1
如果您想要t
中的任何列,則需要使用聚合 function。 例如COUNT(*)
來計算事務數。
另請注意,我將LEFT JOIN
更改為INNER JOIN
。 您需要匹配才能滿足HAVING
條件,因此不需要外連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.