简体   繁体   English

MySQL Dense_Rank() 和 Max() 函数在同一个语句中不起作用

[英]MySQL Dense_Rank() and Max() functions not working in the same statement

I started with this MySQL query which worked fine:我从这个运行良好的 MySQL 查询开始:

select 
h.id,
h.name,
count(distinct c.sales_id)
from customers h join sales c on h.id=c.id
group by 1,2
order by 3 desc, 2 desc

However, now I want to add 2 additional columns in the same statement:但是,现在我想在同一个语句中添加 2 个额外的列:

  1. The first column should be the max value from the 'count(distinct c.sales_id)' column --> max(count(distinct c.sales_id))第一列应该是 'count(distinct c.sales_id)' 列的max(count(distinct c.sales_id)) --> max(count(distinct c.sales_id))
  2. The second column should add a dense_rank by the 'count(distinct c.sales_id)' column --> dense_rank() over (order by count(distinct c.sales_id))第二列应该通过'count(distinct c.sales_id)'列-> dense_rank() over (order by count(distinct c.sales_id))添加一个dense_rank

I have a hard time adding these two columns as I keep getting an aggregation error with this query:我很难添加这两列,因为我不断收到此查询的聚合错误:

select 
h.id,
h.name,
count(distinct c.sales_id),
max(count(distinct c.sales_id)),
dense_rank() over (order by count(distinct c.sales_id))
from customers h join sales c on h.id=c.id
group by 1,2
order by 3 desc, 2 desc

Can someone help?有人可以帮忙吗?

You might be very close to a solution.您可能非常接近解决方案。

In SQL, one can't max a count.在 SQL 中,不能最大化计数。
But one can max OVER a count.但是一个人最多可以超过一个计数。

So this should work in MySql 8.0所以这应该适用于 MySql 8.0

(untested on sample data) (未经样本数据测试)

select 
h.id,
h.name,
count(distinct c.sales_id) as total_uniq_sales,
MAX(count(distinct c.sales_id)) OVER (),
dense_rank() over (order by count(distinct c.sales_id))
from customers h 
join sales c on h.id=c.id
group by h.id, h.name
order by total_uniq_sales desc, h.name desc

The reason behind that is that the window functions are processed after the aggregation functions.这背后的原因是窗口函数是在聚合函数之后处理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM