不要在分组依据中包含 select 列

Do not include select columns in group by

这是我的表格(仅包括相关列)

Table: carts
address_id - integer

Table: addresses
name - varchar
phone - varchar

Table: orders
order_number - integer (this is the foreign key for cart table)

我想获取 phone 只订购过一次的客户数量,所以我构建了以下查询

select addresses.phone 
from orders 
   inner join carts on orders.order_number = carts.id 
   inner join address on carts.address_id = addresses.id 
group by addresses.phone 
having count(orders.*) = 1;

效果很好!但我还需要 select 客户姓名和订单号,我将 select 语句更新为

select addresses.phone, addresses.name, orders.order_number ...

现在,postgres 敦促我将这些列包含在 GROUP BY 子句中,但这不会 return 我想要的结果。

我尝试使用如下子查询,这似乎得到了我想要的结果

select addresses.phone, (select ad.name from addresses ad where ad.phone = addresses.phone) ...

但是使用子查询是解决这个问题的唯一方法吗?或者有什么 simpler/optimal 方法吗?

您可以使用 window function 实现此目的,它不需要对所有内容进行分组:

select *
from (
  select addresses.phone, addresses.name, orders.order_number, 
         count(orders.order_number) over (partition by addresses.phone) as cnt
  from orders 
     inner join carts on orders.order_number = carts.id 
     inner join address on carts.address_id = addresses.id 
) t 
where cnt = 1;