SQL查询从年份范围返回“最多指定”,作为列表(使用新列)

时间:2013-11-19 23:09:44

标签: mysql

我有一张表(提名),看起来像:

Year  Category      Artist-Name                Title          Album
1980  AlbumOfYear   Michael Jackson            Thriller       Thriller
1980  ...           ...
1981  ...           ...
1982  ...           ...

我正在尝试开发一个查询,该查询将从用户输入的年份中返回最多指定的Artist-Name,然后按降序返回列表。这样的事情可能吗? (为查询创建新列并从查询中排名)

类似

Rank   Artist              Nominations
1      Michael Jackson     3
2      Billy Joel          2

3 个答案:

答案 0 :(得分:1)

SET @fromyear = 1980;
SET @toyear = 1992;


SET @rank = 0;


SELECT 
@rank:=@rank+1 as rank, 
noms.artist, 
noms.nominations
FROM
    (
    SELECT COUNT(*) as nominations, `Artist-Name` as artist 
    FROM `Nominations`
    WHERE `Year` BETWEEN @fromyear AND @toyear
    GROUP BY `Artist-Name`
    ORDER BY COUNT(*) DESC
    ) as noms;

答案 1 :(得分:0)

以这种方式使用GROUP BY

SET @rank=0;
SELECT @rank:=@rank+1 as rank, Artist-Name as Artist, count(*) as Nominations
WHERE Year = 1980
GROUP BY Artist-Name
ORDER BY Nominations DESC

答案 2 :(得分:0)

这应该适用于oracle。

select rank() over(order by nominations desc),artist,nominations from   
(select artist,count(nominations) nominations from nominations where year between :loweryear and :higheryear group by artist);