[英]Postgresql get List all customer who has 3 or more record transaction
Iam Using postgreSQL.我正在使用 postgreSQL。 I have 2 table with relations
我有 2 张关系表
table customer:表客户:
-------------------------------------------
| customer_id (PK) | first_name | last_name |
-------------------------------------------
| 1 | ogi | tampoo |
| 2 | cimol | comet |
| 3 | cocang | tampoo |
| 4 | bedu | comet |
| 5 | bonjof | tampoo |
table transaction:表事务:
---------------------------------------------------------
| 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 |
question:问题:
Return all customer who has >1 record transaction.
Obviously from transaction table, customer_id = 4 have 3 records
how to query this?
Desired result期望的结果
--------------------------------------------------------------------------------------
| 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 |
what I've try:我尝试过的:
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
It appear that (i dont know if it only postgres), It forced to group by each PRIMARY KEY .看来(我不知道它是否只有 postgres),它强制按每个 PRIMARY KEY 分组。
When I try to group by any other column which is not PK, it return error and demand the PK for group by .当我尝试按任何其他不是 PK 的列进行分组时,它会返回错误并要求 PK 为group by 。
Thank you very much.非常感谢。
Your last query almost works.您的最后一个查询几乎可以工作。 Just select the columns from the customer table -- and join by the primary key:
只需 select 客户表中的列 - 并通过主键连接:
select c.*
from customer c join
transaction t
on t.customer_id = c.customer_id
group by c.customer_id
having count(*) > 1
If you want any columns from t
, then you need to use an aggregation function.如果您想要
t
中的任何列,则需要使用聚合 function。 For instance COUNT(*)
to count the number of transactions.例如
COUNT(*)
来计算事务数。
Also note that I changed the LEFT JOIN
to an INNER JOIN
.另请注意,我将
LEFT JOIN
更改为INNER JOIN
。 You require a match in order to meet the HAVING
condition, so the outer join is not needed.您需要匹配才能满足
HAVING
条件,因此不需要外连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.