gpt4 book ai didi

sql - 不要在分组依据中包含选择列

转载 作者:行者123 更新时间:2023-11-29 12:11:42 27 4
gpt4 key购买 nike

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

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 addresses.phone, addresses.name, orders.order_number ...

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

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

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

但是使用子查询是解决这个问题的唯一方法吗?还是有更简单/最佳的方法?

最佳答案

您可以使用 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;

关于sql - 不要在分组依据中包含选择列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30932989/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com