繁体   English   中英

如何在SQL中将多个聚合结果分组

[英]How to group multiple aggregate results in SQL

我有一个查询,该查询返回ID,用户所在的最高值和最高级别的项目。

我的查询如下:

SELECT id,
MAX(item)   AS highest_item,
MAX(level)  AS highest_level
FROM data
GROUP BY 1
ORDER BY 1;

如何查询数据库,以便获得总数相同但价值最高的唯一用户总数?

您可以获得按所需值分组的count(distcint id)。 例如。 对于这两个值:

select count(distinct id ), highest_item, highest_level

    from ( 
    SELECT id,
    MAX(item)   AS highest_item,
    MAX(level)  AS highest_item
    FROM data
    GROUP BY 1
 ) t 
 group by highest_item, highest_level
 order by count(distinct id ) desc

或用于highest_item

 select count(distinct id ), highest_item

    from ( 
    SELECT id
    MAX(item)   AS highest_item,
    MAX(level)  AS highest_level
    FROM data
    GROUP BY 1
 ) t 
 group by highest_item
order by count(distinct id ) desc

的,最高级别

 select count(distinct id ), highest_level

    from ( 
    SELECT id,
    MAX(item)   AS highest_item,
    MAX(level)  AS highest_level
    FROM data
    GROUP BY 1
 ) t 
 group by highest_level
 order by count(distinct id ) desc

您也可以尝试

Select id,count(Id) from data group by level,item having level=max(level) and item=max(item)

暂无
暂无

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

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