简体   繁体   English

选择2列中的MAX最大值的计数

[英]SELECT Count of MAX value over 2 columns

This has been stumping me for a little bit and I can't seem to get the right query 这让我有些困惑,我似乎无法得到正确的查询

Table 1: 表格1:

╔════════════════════╗
║     Record   Level ║
╠════════════════════╣
║     1         0    ║
║     1         1    ║
║     1         2    ║
║     2         3    ║
║     2         4    ║
║     2         5    ║
║     3         2    ║
╚════════════════════╝

What I'm looking for is the count of the max level of each unique record ie should return 我正在寻找的是每个唯一记录的最大级别的计数,即应该返回

╔════════════════════╗
║ level 2, 2 records ║
║ level 5, 1 record  ║
╚════════════════════╝

etc. 等等

You can use a sub-query to first determine the max levels and then do a count of the max levels, as below: 您可以使用子查询来首先确定最大级别,然后对最大级别进行计数,如下所示:

SELECT
    max_level,
    count(*)
FROM
(
    SELECT
        max(level) AS max_level
    FROM table1
    GROUP BY Record
) max_levels
GROUP BY max_level
ORDER BY max_level;

You need two steps, (1) find the max level for each record and (2) count the records that have that max level for each level. 您需要两个步骤,(1)找到每个记录的最大级别,(2)计算每个级别具有该最大级别的记录。 You can use a subquery to create the Record/MaxLevel table: 您可以使用子查询来创建Record / MaxLevel表:

SELECT MaxLevel, COUNT(*) AS RecordCount
FROM (
        SELECT Record, MAX(Level) AS MaxLevel
        FROM Table1
        GROUP BY Record
    )
GROUP BY MaxLevel

You may also want a third select to make sure you include all levels if you want 0 counts for levels that have no records with their value as the max level. 如果您希望没有记录且其值作为最大级别的级别的计数为0,则可能还需要第三个选择来确保包括所有级别。 You can select the distinct values for level as subquery 'a' and left join into the max level counts subquery 'b'. 您可以为级别选择不同的值作为子查询“ a”,然后左联接到最大级别计数子查询“ b”中。

SELECT a.Level, COUNT(b.Record) AS RecordCount
FROM (SELECT DISTINCT Level FROM Table1) a
LEFT OUTER JOIN (
        SELECT Record, MAX(Level) AS MaxLevel
        FROM Table1
        GROUP BY Record
    ) b ON b.MaxLevel = a.Level
GROUP BY a.Level

You need a subquery to extract maximum level for each record number. 您需要一个子查询来提取每个记录号的最大级别。 Then you outer query will count total appearances of each level as the maximum level. 然后,您的外部查询会将每个级别的总外观计为最大级别。

SELECT COUNT(*) AS c, Level FROM
(
    SELECT MAX(Level) AS Level
    FROM Table1 
    GROUP BY Record
) l
GROUP BY Level
select count(0), level
from table t
where level>= all (select level from table where t.record=record)
group by level

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

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