SQL - 计算分组条目,然后获取按日期分组的最大值

时间:2010-06-16 19:13:09

标签: sql sqlite aggregate-functions

我有一个sqlite表,连续播放每个播放的曲目,播放日期/时间 现在我将计算所有艺术家的剧本,按天分组,然后找到每天最大游戏数量的艺术家。 我使用了这个查询

SELECT COUNT(ARTISTID) AS artistcount,
       ARTIST AS artistname,
       strftime('%Y-%m-%d', playtime) AS day_played
FROM playcount
GROUP BY artistname, day_played

获得此结果

"93"|"The Skygreen Leopards"|"2010-06-16"
"2" |"Arcade Fire"          |"2010-06-15"
"2" |"Dead Kennedys"        |"2010-06-15"
"2" |"Wolf People"          |"2010-06-15"
"3" |"16 Horsepower"        |"2010-06-15"
"3" |"Alela Diane"          |"2010-06-15"
"46"|"Motorama"             |"2010-06-15"
"1" |"Ariel Pink's Haunted" |"2010-06-14"

然后我尝试查询这个虚拟表,但我总是在artistname中得到错误的结果。

SELECT MAX(artistcount), artistname , day_played 
FROM
(
SELECT COUNT(ARTISTID) AS artistcount,
       ARTIST AS artistname,
       strftime('%Y-%m-%d', playtime) AS day_played
FROM playcount
GROUP BY artistname
)
GROUP BY strftime('%Y-%m-%d',day_played)

导致此

"93"|"lilium"     |"2010-06-16"
"46"|"Wolf People"|"2010-06-15"
"30"|"of Montreal"|"2010-06-14"

但是艺术家的名字是假的。 我认为通过白天的分组,它只使用最后一位艺术家,或者左右。 我测试了像INNER JOIN或GROUP BY这样的东西......在试验和错误中,我阅读了类似问题的例子,但总是迷失在列名和东西中 (我有点筋疲力尽)

我希望有人可以给我一个提示。谢谢你

2 个答案:

答案 0 :(得分:1)

这正是发生的事情。我甚至不希望这个查询运行 - 因为你在SELECT子句中有“artistname”但在GROUP BY中没有,我希望你正在使用的SQL引擎拒绝执行查询。 / p>

要解决此问题,只需在外部查询中将“artistname”添加到GROUP BY:

SELECT MAX(artistcount), artistname , day_played 
FROM
(
SELECT COUNT(ARTISTID) AS artistcount,
ARTIST AS artistname,strftime('%Y-%m-%d', playtime) AS day_played
FROM playcount
GROUP BY artistname
)
GROUP BY artistname, strftime('%Y-%m-%d',day_played)

答案 1 :(得分:0)

我读完之后找到了一条路: http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/ 但它感觉很愚蠢,也许有人可以提示如何优化它。

我创建了一个名为 max_play_by_artist 的sqlite 视图,其输出按日期分组的所有游戏数量

CREATE VIEW "max_play_by_artist"
AS
    SELECT COUNT(artistid) AS artistcount,
    artist AS artistname,
    strftime('%Y-%m-%d', playtime) AS day_played,
    artistid as id
    FROM playcount
    GROUP BY artistid,day_played

然后我用以下语句查询视图

SELECT b.artistcount, b.artistname, b.day_played, b.id
FROM 
(
    SELECT day_played, MAX(artistcount) as max_count
    FROM max_play_by_artist
    GROUP BY day_played
) AS a
INNER JOIN max_play_by_artist AS b
ON b.day_played = a.day_played
AND b.artistcount = a.max_count

这给了我想要的结果。