我有一个带有ID,AID和Year字段的表。如何在集合中找到最近的共同年份(常见的AID组成集合)
ID AID Year
---------
1 1 2001
2 1 2002
3 1 2003
4 1 2004
5 2 2003
6 2 2004
7 2 2005
8 3 2004
9 3 2005
10 3 2006
最近的普通年份2004
答案 0 :(得分:2)
我相信这是最简单的方法。
查询
SELECT
Year
FROM
t
GROUP BY
Year
HAVING
COUNT(*) = (SELECT COUNT(DISTINCT t.AID) FROM t)
结果
| Year |
| ---- |
| 2004 |
请参阅demo
此查询使它更容易理解
查询
SELECT
Year
, COUNT(*) AS count_per_AID
, (SELECT COUNT(DISTINCT t.AID) FROM t) AS unique_count_per_AID
, (COUNT(*) = (SELECT COUNT(DISTINCT t.AID) FROM t)) AS most_common_value
FROM
t
GROUP BY
Year
结果
| Year | count_per_AID | unique_count_per_AID | most_common_value |
| ---- | -------------- | -------------------- | ----------------- |
| 2001 | 1 | 3 | 0 |
| 2002 | 1 | 3 | 0 |
| 2003 | 2 | 3 | 0 |
| 2004 | 3 | 3 | 1 |
| 2005 | 2 | 3 | 0 |
| 2006 | 1 | 3 | 0 |
此查询返回所有普通年份,而不是最新的普通年份 年。
确实要感谢您的评论。
解决方法是使用查询
SELECT
Year
FROM
t
GROUP BY
Year
HAVING
COUNT(*) = (SELECT COUNT(DISTINCT t.AID) FROM t)
ORDER BY
t.Year DESC
LIMIT 1
;
请参阅demo