简体   繁体   English

MySQL条件计数基于另一列中的值

[英]MySQL Conditional count based on a value in another column

I have table that looks like this: 我有这样的表:

id rank
a  2
a  1
b  4
b  3
c  7
d  1
d  1
e  9

I need to get all the distinct rank values on one column and count of all the unique id's that have reached equal or higher rank than in the first column. 我需要在一列上获取所有不同的排名值,并计算已达到比第一列相同或更高排名的所有唯一ID。

So the result I need would be something like this: 所以我需要的结果将是这样的:

rank count
1    5
2    4
3    3
4    3
7    2
9    1

I've been able to make a table with all the unique id's with their max rank: 我已经能够创建一个具有所有最大ID的唯一ID的表格:

SELECT 
MAX(rank) AS 'TopRank',
id
FROM myTable
GROUP BY id

I'm also able to get all the distinct rank values and count how many id's have reached exactly that rank: 我还能够获得所有不同的等级值,并计算出多少个ID恰好达到了该等级:

SELECT
DISTINCT TopRank AS 'rank',
COUNT(id) AS 'count of id'
FROM
  (SELECT 
  MAX(rank) AS 'TopRank',
  id
  FROM myTable
  GROUP BY id) tableDerp
GROUP BY TopRank
ORDER BY TopRank ASC

But I don't know how to get count of id's where the rank is equal OR HIGHER than the rank in column 1. Trying SUM(CASE WHEN TopRank > TopRank THEN 1 END) naturally gives me nothing. 但是我不知道如何获得等于或高于第1列中的ID的计数。尝试使用SUM(在TopRank> TopRank THEN 1 END的情况下)自然不会给我任何帮助。 So how can I get the count of id's where the TopRank is higher or equal to each distinct rank value? 那么,如何获得TopRank高于或等于每个不同等级值的id的计数? Or am I looking in the wrong way and should try something like running totals instead? 还是我看错方向,应该尝试运行总计? I tried to look for similar questions but I think I'm completely on a wrong trail here since I couldn't find any and this seems a pretty simple problem that I'm just overthinking somehow. 我试图寻找类似的问题,但我认为这里完全错了,因为我找不到任何问题,这似乎是一个非常简单的问题,我只是以某种方式进行了思考。 Any help much appreciated. 任何帮助,不胜感激。

One approach is to use a correlated subquery. 一种方法是使用相关子查询。 Just get the list of ranks and then use a correlated subquery to get the count you are looking for: 只需获取等级列表,然后使用相关子查询即可获取您要查找的计数:

SELECT r.rank,
       (SELECT COUNT(DISTINCT t2.id)
        FROM myTable t2
        WHERE t2.rank >= r.rank
       ) as cnt
FROM (SELECT DISTINCT rank FROM myTable) r;

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

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