真的希望有人可以帮助我,因为我对SQL很垃圾!
我的表格如下所示,我需要显示每年最流行的名字......
+---------+----+-----------+------+-----------+-----+
|UNIQUE_ID|YEAR| COUNTY|GENDER| NAME|COUNT|
+---------+----+-----------+------+-----------+-----+
| 1|2013|ST LAWRENCE| M| GAVIN| 9|
| 2|2013|ST LAWRENCE| M| LEVI| 9|
| 3|2013| NEW YORK| M| LOGAN| 44|
| 4|2013| NEW YORK| M| HUDSON| 49|
| 5|2013| NEW YORK| M| GABRIEL| 50|
| 6|2013| NEW YORK| M| THEODORE| 51|
| 7|2013| KINGS| F| ELIZA| 16|
| 8|2013| KINGS| F| MADELEINE| 16|
| 9|2013| KINGS| F| ZARA| 16|
| 10|2013| KINGS| F| DAISY| 16|
| 11|2013| NEW YORK| M| JONATHAN| 51|
| 12|2013| NEW YORK| M|CHRISTOPHER| 52|
| 13|2013| SUFFOLK| M| LUKE| 49|
| 14|2013| NEW YORK| M| JACKSON| 53|
| 15|2013| SUFFOLK| M| JACKSON| 49|
| 16|2013| NEW YORK| M| JOSHUA| 53|
| 17|2013| NEW YORK| M| AIDEN| 53|
| 18|2013| SUFFOLK| M| BRANDON| 50|
| 19|2013| KINGS| F| JUDY| 16|
| 20|2013|ST LAWRENCE| M| MASON| 8|
+---------+----+-----------+------+-----------+-----+
......继续成千上万行...
我知道我必须按年计算一笔数和一组数,但我尝试的任何东西似乎都无效。
输出应该看起来像......
+----+--------+-----------+
|YEAR|TOTAL |MOST_POPULAR|
+----+--------+-----------+
|2016| 12419| GAVIN|
|2015| 22119| LEVI|
|2014| 44113| LOGAN|
|2013| 12349| HUDSON|
|2012| 15024| GABRIEL|
|2011| 55311| THEODORE|
|2010| 13446| ELIZA|
|2009| 12346| MADELEINE|
|2008| 13456| ZARA|
|2007| 21126| DAISY|
|2006| 13451| JONATHAN|
|2005| 52241|CHRISTOPHER|
|2004| 14923| LUKE|
+----+-----+-----------+
请帮忙!
答案 0 :(得分:1)
这应该有帮助 -
SELECT YEAR,TOTAL, NAME AS MOST_POPULAR
FROM (
SELECT YEAR,NAME,TOTAL, DENSE_RANK() OVER (PARTITION BY YEAR ORDER BY TOTAL DESC) AS RNK
FROM (
SELECT YEAR,SUM(CNT) AS TOTAL, NAME
FROM TAB1
GROUP BY YEAR,NAME
ORDER BY 2 DESC
)
) WHERE RNK = 1
ORDER BY YEAR DESC;
答案 1 :(得分:0)
如果以下代码适合您,您可以尝试:
SELECT year, total, Name AS 'Most_popular'
FROM tablename
WHERE name IN (SELECT year, name, MAX(count)
FROM tablename
GROUP BY year, name)
ORDER BY YEAR DESC