找到具有最大崩溃率的年份?

时间:2012-04-05 02:55:08

标签: mysql sql

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 个答案:

答案 0 :(得分: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;

答案 1 :(得分:4)

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

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

答案 2 :(得分:3)

不确定为什么你在crash_year上有MAX。去掉它。所以问题是:

  

找出具有最大崩溃率的年份?

在MySQL和PostgreSQL中:

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

在SQLServer中:

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

答案 3 :(得分: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的味道添加为标签我们可能更具体。