【问题标题】:How could I use the select statement on feature from a subquery ? (Postgree)如何在子查询中使用 select 语句? (Postgres)
【发布时间】:2021-06-19 22:13:21
【问题描述】:

我正在接受面试培训并试图解决一个问题,我想为每个城市找出花费最多的客户。我得到了按城市花费的最大金额的好结果,但是当我尝试检索花费此金额的客户的姓名和姓氏时出现错误。有没有一种有效的方法来做到这一点?谢谢!

select max(total_payment),X.city, X.firstname, X.lastname
from (
select sum(amount) as total_payment, c.customer_id, cit.city_id, cit.city as city, c.first_name as firstname, c.last_name as lastname
from payment p
inner join customer as c on p.customer_id=c.customer_id
inner join address as ad on c.address_id=ad.address_id
inner join city as cit on ad.city_id=cit.city_id
group by c.customer_id, cit.city_id
order by city
) as X
group by X.city

目标结果列: 每个城市花费最多的客户的姓名和姓氏。

120,巴黎,尼古拉斯,杜邦

130,马德里,劳尔,加西亚

70,伦敦,戴夫,高盛

【问题讨论】:

  • 为什么选择 max(total_payment),X.city, X.firstname, X.lastname,但是 GROUP BY 只能按 X.city
  • 你好,因为我只需要按城市花费最多的人
  • 好的。但是你只需要选择 max(total_payment),X.city from(...)group by X.city
  • 我也想要花最多的人的名字
  • 如果你有两个?如果您提供一些示例数据和所需的输出会更好,因为现在看起来您需要一些窗口计算

标签: sql postgresql subquery aggregate-functions


【解决方案1】:

你想要窗口函数:

select cc.*
from (select sum(p.amount) as total_payment, c.customer_id, cit.city_id, 
             cit.city as city, c.first_name as firstname, c.last_name as lastname,
             row_number() over (partition by cit.city order by sum(p.amount) desc) as seqnum
      from payment p join
           customer c
           on p.customer_id = c.customer_id join
           address ad
           on c.address_id = ad.address_id join
           city cit
           on ad.city_id = cit.city_id
      group by c.customer_id, cit.city_id
     ) cc
where seqnum = 1;

请注意,您的查询有两个错误会导致面试失败:

  1. 您在子查询中使用ORDER BY。根据标准和大多数数据库,ORDER BY 要么不被允许要么被忽略。
  2. 在您的外部查询中,GROUP BY 列与未聚合的 SELECT 列不一致。再一次,这违反了标准,并且大多数数据库都会返回语法错误。

【讨论】:

  • 我还有很多东西要学,非常感谢!
  • @robin_data 。 . .如果这回答了您的问题,您可以接受答案。
  • 当然我刚刚做了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
  • 2022-01-02
  • 1970-01-01
  • 2014-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多