【问题标题】:Multiple Aggregation in SQLSQL中的多重聚合
【发布时间】:2021-03-21 10:50:18
【问题描述】:
loan_no   loan_amt   contact date  customer_id  salesman_id 

我有下表。我需要以某种方式为拥有多个loan_no 的人获取loan_no 的平均值和loan_amt 的平均值。我需要以某种方式插入 avg 和 count 函数。

我正在为此苦苦挣扎。我也在考虑一个枢轴函数。

如果有人能推荐一个 SQL 代码,我将不胜感激

到目前为止我的努力:

select count (loan_no), tcustomer_id
from table
group by customer_id
having count (loan_no) > 1 

现在我只是不知道如何也包含 avg 函数。

【问题讨论】:

  • 请将数据发布为文本而不是外部图像。还向我们表明您尝试通过发布您尝试过的任何查询来自己解决这个问题。
  • 请将您的数据以文本形式发布。不要链接到图像。阅读:meta.stackoverflow.com/questions/285551/…。那么,你走了多远?你用过GROUP BY吗?
  • 请在您的问题中包含示例数据和所需的输出minimal-reproducible-example
  • 我添加了列应该是什么样子以及我现在写的代码
  • loan_amt 的平均值为AVG(loan_amt)loan_no 的平均值为 AVG(loan_no)。还是你想要别的东西?如果有,是什么?

标签: sql count average


【解决方案1】:

不知道为什么你需要平均 Loan_no 但你仍然可以通过 -


select customer_id, avg(loan_no), avg(loan_amt)
  from (select *, count(*) over(partition by customer_id) cnt
          from table)
 where cnt > 1
 group by customer_id

【讨论】:

    【解决方案2】:

    您可以使用两个级别的聚合:

    select avg(num_loans), sum(total) / sum(num_loans)
    from (select customer_id, count(*) as num_loans, sum(loan_amt) as total
          from table
          group by customer_id
         ) t 
    where num_loans > 1;
    

    【讨论】:

      猜你喜欢
      • 2021-02-23
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多