[英]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.