以下是我的表格(仅包括相关栏目)
Table: carts
address_id - integer
Table: addresses
name - varchar
phone - varchar
Table: orders
order_number - integer (this is the foreign key for cart table)
我想获取仅订购一次的客户的电话号码,因此我构建了以下查询
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 addresses.phone, addresses.name, orders.order_number ...
现在,postgres敦促我在GROUP BY
子句中包含这些列,但这不会给我带来预期的结果。
我尝试使用子查询如下,这似乎得到了我想要的结果
select addresses.phone, (select ad.name from addresses ad where ad.phone = addresses.phone) ...
但是使用子查询是解决这个问题的唯一方法吗?或者有更简单/最佳的方式吗?
答案 0 :(得分:2)
您可以使用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;