这让我感到有点困难,我似乎无法获得正确的查询
表1:
╔════════════════════╗
║ Record Level ║
╠════════════════════╣
║ 1 0 ║
║ 1 1 ║
║ 1 2 ║
║ 2 3 ║
║ 2 4 ║
║ 2 5 ║
║ 3 2 ║
╚════════════════════╝
我正在寻找的是每条唯一记录的最高等级数,即应该返回
╔════════════════════╗
║ level 2, 2 records ║
║ level 5, 1 record ║
╚════════════════════╝
等
答案 0 :(得分:3)
您可以使用子查询首先确定最高级别,然后计算最高级别,如下所示:
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;
答案 1 :(得分:3)
您需要两个步骤,(1)找到每条记录的最高级别,以及(2)计算每个级别具有该最高级别的记录。您可以使用子查询来创建Record / MaxLevel表:
SELECT MaxLevel, COUNT(*) AS RecordCount
FROM (
SELECT Record, MAX(Level) AS MaxLevel
FROM Table1
GROUP BY Record
)
GROUP BY MaxLevel
您可能还需要第三个选择,以确保包含所有级别,如果您希望0级别没有记录,其值为最大级别。您可以选择级别的不同值作为子查询'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
答案 2 :(得分:3)
您需要一个子查询来提取每个记录号的最大级别。然后,外部查询将计算每个级别的总体外观作为最大级别。
SELECT COUNT(*) AS c, Level FROM
(
SELECT MAX(Level) AS Level
FROM Table1
GROUP BY Record
) l
GROUP BY Level
答案 3 :(得分:2)
select count(0), level
from table t
where level>= all (select level from table where t.record=record)
group by level