2012-04-05 45 views
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

添加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; 
+0

謝謝你,忘了極限的事情。 – 2012-04-05 03:01:28

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比頂部1.我想,如果你加入你的SQL風味的標籤,我們可以更具體。

4

取決於你使用SQL數據庫引擎。一些在SELECT之後立即使用TOP 1,一些在ORDER BY子句之後使用LIMIT 1。

此外,您不需要在crash_year的第一個實例周圍使用MAX()。

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