在 SQL MS Access 中添加 Max(Count(column))
Add Max(Count(column)) in SQL MS Access
我有以下示例数据集,如您所见,X 列是 class ID,Y 列是每个 class 名称,最后 Z 列是其他大学 class 用于每个主题的 ID。目标是通过 X 分组获得 X 和 Z,并获得 Z(其他大学)使用的最常见 ID。
Sheet 1:
X
Y
Z
123
22
122
123
22
123
123
22
122
256
21
256
256
21
255
341
33
400
341
33
400
结果应该是:
X
Z
123
122
256
255
341
400
我尝试添加以下查询,但它只返回所有 table 中的最大值,而不仅仅是 Z 列中的每个值。
SELECT Sheet1.X, Sheet1.Z
FROM Sheet1
GROUP BY Sheet1.X, Sheet1.Z
HAVING COUNT(Sheet1.Z) =
(SELECT MAX(sheet2.count) FROM
(SELECT Sheet1.X, Sheet1.Z, COUNT(Sheet1.Z) AS count
FROM Sheet1
GROUP BY Sheet1.X, Sheet1.Z) as sheet2);
对我做错了什么有什么建议吗?
这在 MS Access 中是一个真正的痛苦。但是如果你想要每个 X
一个 行,那么你可以这样做:
SELECT s1.X, s1.Z
FROM Sheet1 as s1
GROUP BY s1.X, s1.Z
HAVING s1.Z = (SELECT TOP (1) s2.Z
FROM Sheet1 as s2
WHERE s2.X = s1.X
GROUP BY s2.Z
ORDER BY COUNT(*) DESC, s2.Z
);
如果您想要在并列的情况下多行,则使用:
SELECT s1.X, s1.Z
FROM Sheet1 as s1
GROUP BY s1.X, s1.Z
HAVING COUNT(*) IN (SELECT TOP (1) COUNT(*)
FROM Sheet1 as s2
WHERE s2.X = s1.X
GROUP BY s2.Z
);
我应该注意到,这在任何其他数据库中都会更简单。
我有以下示例数据集,如您所见,X 列是 class ID,Y 列是每个 class 名称,最后 Z 列是其他大学 class 用于每个主题的 ID。目标是通过 X 分组获得 X 和 Z,并获得 Z(其他大学)使用的最常见 ID。
Sheet 1:
X | Y | Z |
---|---|---|
123 | 22 | 122 |
123 | 22 | 123 |
123 | 22 | 122 |
256 | 21 | 256 |
256 | 21 | 255 |
341 | 33 | 400 |
341 | 33 | 400 |
结果应该是:
X | Z |
---|---|
123 | 122 |
256 | 255 |
341 | 400 |
我尝试添加以下查询,但它只返回所有 table 中的最大值,而不仅仅是 Z 列中的每个值。
SELECT Sheet1.X, Sheet1.Z
FROM Sheet1
GROUP BY Sheet1.X, Sheet1.Z
HAVING COUNT(Sheet1.Z) =
(SELECT MAX(sheet2.count) FROM
(SELECT Sheet1.X, Sheet1.Z, COUNT(Sheet1.Z) AS count
FROM Sheet1
GROUP BY Sheet1.X, Sheet1.Z) as sheet2);
对我做错了什么有什么建议吗?
这在 MS Access 中是一个真正的痛苦。但是如果你想要每个 X
一个 行,那么你可以这样做:
SELECT s1.X, s1.Z
FROM Sheet1 as s1
GROUP BY s1.X, s1.Z
HAVING s1.Z = (SELECT TOP (1) s2.Z
FROM Sheet1 as s2
WHERE s2.X = s1.X
GROUP BY s2.Z
ORDER BY COUNT(*) DESC, s2.Z
);
如果您想要在并列的情况下多行,则使用:
SELECT s1.X, s1.Z
FROM Sheet1 as s1
GROUP BY s1.X, s1.Z
HAVING COUNT(*) IN (SELECT TOP (1) COUNT(*)
FROM Sheet1 as s2
WHERE s2.X = s1.X
GROUP BY s2.Z
);
我应该注意到,这在任何其他数据库中都会更简单。