2010-06-16 116 views
2

分組的最高值我有一個SQLite表保持每播放的曲目中的一排打日期/時間 現在我將計算所有藝術家的戲劇,按天分組然後每天以最大playcount找到藝術家。 我用這個查詢SQL - 計數分組條目,然後獲得通過日期

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" 

但藝術家的名字是假的。 我想通過一天的分組,它只是用過去的藝術家,還是如此。 我測試狀內的東西JOIN或GROUP BY ... HAVING在試錯,我讀的類似問題的例子,但總是迷失在COLUMNNAMES和東西 (我有點燒壞了)

我希望有人能給我一個提示。感謝中號

回答

1

這正是發生了什麼。我甚至不會想到這個查詢運行 - 因爲你已經得到了「ARTISTNAME」 SELECT子句中,但不在GROUP BY,我期望你正在使用的SQL引擎拒絕執行查詢。

要解決它,只需添加「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) 
+0

用藝術家名稱再次分組會導致我發佈的第一個表格輸出。也許我需要第三個選擇和「加盟」兩種結果^^。 – Marcus 2010-06-16 19:30:32

+0

與MySQL類似,SQLite擁有關於GROUP BY子句的這個「特性」,您不必遵循SQL標準並可以省略列...... – 2010-06-16 19:31:04

+0

這是一個可怕的「特性」,因爲它導致了類似的東西。無論如何,將它添加到GROUP BY應該清理問題。 – SqlRyan 2010-06-16 20:31:22

0

我已經找到一種方法看完這個: http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/ 但感覺愚蠢的,也許有人可以給出一個提示如何優化這個。

我創建一個SQLite 視圖稱爲max_play_by_artist其輸出由day_played

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 

分組的所有playcounts然後我查詢視圖與下面的語句

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 

這給了我期望的結果。