简体   繁体   English

在 SQL MS Access 中添加 Max(Count(column))

[英]Add Max(Count(column)) in SQL MS Access

I have the following example dataset and as you can see the column X is the class ID, column Y is each class name, and finally column Z is the other universities class ID used for each subject.我有以下示例数据集,如您所见,X 列是 class ID,Y 列是每个 class 名称,最后 Z 列是用于每个主题的其他大学 class ID。 The goal is to get X, and Z with a grouping by X and get the most common ID used by Z (Other universities).目标是通过 X 分组获得 X 和 Z,并获得 Z(其他大学)使用的最常用 ID。

Sheet 1:表 1:

X X Y Z Z
123 123 22 22 122 122
123 123 22 22 123 123
123 123 22 22 122 122
256 256 21 21 256 256
256 256 21 21 255 255
341 341 33 33 400 400
341 341 33 33 400 400

The outcome should be:结果应该是:

X X Z Z
123 123 122 122
256 256 255 255
341 341 400 400

I tried by adding the following query, but it is only returning the maximum from all the the table but not only for each value in column Z.我尝试通过添加以下查询,但它只返回所有表中的最大值,而不仅仅是 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);

Any suggestion of what I am doing wrong?关于我做错了什么的任何建议?

This is a real pain in MS Access.这是 MS Access 的一大痛点。 But if you want one row per X , then you can do:但是,如果您想要每个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
              );

If you want multiple rows in the event of ties, then use:如果您想要多行以防出现平局,请使用:

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
                   );

I should note that this would be simpler in just about any other database.我应该注意到,这在几乎任何其他数据库中都会更简单。

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

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