获取每组的最大数量

时间:2017-01-26 17:00:58

标签: sql ms-access

我在MS访问中有一个表有2个字段(payroll和absenceReason)。每个缺席实例都有一条记录。

我正在尝试编写SQL查询以返回每个人最常见的缺席原因。我确信有一种简单的方法可以做到这一点,但我似乎无法得到它。我试过写下面的查询:

SELECT payroll, reason, max(count)
FROM
(
SELECT payroll, reason, count(reason) as count
FROM table1
GROUP BY payroll, reason
) 
GROUP BY payroll, reason

但这会让每个人都有理由。如果我从GROUP BY子句中删除原因,那么它不起作用,因为我没有在select部分中聚合原因。谁能指出我哪里出错?

由于

1 个答案:

答案 0 :(得分:1)

一种方法使用having

SELECT payroll, reason, count(reason) as count
FROM table1 as t1
GROUP BY reason, payroll
HAVING t1.reason = (SELECT TOP 1 tt1.reason
                    FROM table1 as tt1
                    WHERE tt1.payroll = t1.payroll
                    GROUP BY tt1.reason
                    ORDER BY COUNT(*) DESC, tt1.reason
                   );