【发布时间】:2021-03-13 09:05:45
【问题描述】:
我正在使用 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
- 错误:列“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 的列进行分组时,它会返回错误并要求 group by 的 PK。
非常感谢。
【问题讨论】:
标签: sql postgresql group-by left-join having-clause