如何在SQL

时间:2017-08-29 19:23:39

标签: mysql

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

我的查询如下:

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

如何查询数据库,以便获得最高级别且具有相同最高价值项目的唯一身份用户总数?

2 个答案:

答案 0 :(得分:0)

您可以按所需的值分组计数(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

of high_level

 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

答案 1 :(得分:0)

你也可以尝试这个

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