1
SELECT MAX(crash_year) AS crash_year, COUNT(crash_year) AS COUNT 
FROM nyccrash 
GROUP BY crash_year 
ORDER BY COUNT(crash_year) DESC;

该语句将返回 20 年的整个范围。但是我如何只检索第一行?

+------------+-------+
| crash_year | count |
+------------+-------+
|       1999 |   862 |
|       1990 |   847 |
|       1992 |   812 |
|       1991 |   810 |
|       1993 |   806 |
|       2000 |   803 |
|       1994 |   782 |
|       1989 |   763 |
|       2001 |   729 |
|       1995 |   698 |
|       1997 |   672 |
|       1996 |   671 |
|       1998 |   665 |
|       2002 |   497 |
|       2003 |   419 |
|       2006 |   384 |
|       2004 |   377 |
|       2007 |   364 |
|       2005 |   363 |
+------------+-------+
4

4 回答 4

4

添加LIMIT 1到查询的末尾,因此:

SELECT MAX(crash_year) AS crash_year, COUNT(crash_year) AS COUNT 
FROM nyccrash 
GROUP BY crash_year 
ORDER BY COUNT(crash_year) DESC
LIMIT 1;
于 2012-04-05T02:57:21.597 回答
4

取决于您使用的 SQL 数据库引擎。有些在 SELECT 之后使用 TOP 1,有些在 ORDER BY 子句之后使用 LIMIT 1。

此外,您不需要在 crash_year 的第一个实例周围使用 MAX()。

于 2012-04-05T03:01:56.763 回答
3

不知道为什么你有一个MAXcrash_year。去掉它。所以问题是:

找出崩溃率最高的年份?

在 MySQL 和 PostgreSQL 中:

SELECT crash_year
FROM nyccrash 
GROUP BY crash_year 
ORDER BY COUNT(crash_year) DESC
LIMIT 1

在 SQL Server 中:

SELECT TOP 1 crash_year
FROM nyccrash 
GROUP BY crash_year 
ORDER BY COUNT(crash_year) DESC

在 DB2 中:

SELECT crash_year
FROM nyccrash 
GROUP BY crash_year 
ORDER BY COUNT(crash_year) DESC
FETCH FIRST 1 ROWS ONLY
于 2012-04-05T03:15:09.463 回答
2
SELECT TOP 1
    crash_year, COUNT
FROM
(
    SELECT MAX(crash_year) AS crash_year, COUNT(crash_year) AS COUNT 
    FROM nyccrash 
    GROUP BY crash_year 
    ORDER BY COUNT(crash_year) DESC;
) AS T

刚刚看到一个 LIMIT 1 与一个 top 1。我想如果你将你的 SQL 风格添加为标签,我们可以更具体。

于 2012-04-05T02:57:03.990 回答