我从这个运行良好的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
但是,现在我想在同一条语句中添加2个其他列:
max(count(distinct c.sales_id))
dense_rank() over (order by count(distinct c.sales_id))
我很难添加这两列,因为此查询不断导致聚合错误:
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
有人可以帮忙吗?
答案 0 :(得分:0)
您可能非常接近解决方案。
在SQL中,最多不能计数。
但是一个人最多可以超过一个计数。
所以这应该在MySql 8.0中起作用
(未经测试的样本数据)
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
其背后的原因是窗口函数在聚合函数之后进行处理。