Postgresql get 列出所有有3个或更多记录交易的客户

Postgresql get List all customer who has 3 or more record transaction

我正在使用 postgreSQL。 我有 2 table 关系

table 客户:

-------------------------------------------
| customer_id (PK) | first_name | last_name  |
-------------------------------------------
| 1                | ogi        |    tampoo  |
| 2                | cimol      |    comet   |
| 3                | cocang     |    tampoo  |
| 4                | bedu       |    comet   |
| 5                | bonjof     |    tampoo  |

table 交易:

---------------------------------------------------------
| 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  |

我的尝试:

  1. (return 无)
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

  1. 错误:列“cs.customer_id”必须出现在 GROUP BY 子句中或用于聚合函数
    错误:列“tr.transaction_id”必须出现在 GROUP BY 子句中或用于聚合函数
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 的任何其他列分组时,它 return 错误并要求 group by.

的 PK

非常感谢。

您的最后一个查询 几乎 有效。仅 select 来自客户 table 的列——并通过 primary 键加入:

select c.*
from customer c join 
     transaction t
     on t.customer_id = c.customer_id
group by c.customer_id
having count(*) > 1

如果您想要 t 中的任何列,则需要使用聚合函数。例如COUNT(*)统计交易次数

另请注意,我将 LEFT JOIN 更改为 INNER JOIN。您需要匹配才能满足 HAVING 条件,因此不需要外部联接。