2012-04-25 35 views
0

在先前的問題,我問,有人建議MAX(value)語法上alphbetization如何使用GROUP BY檢索CASE字段的字母化優先級結果集?

How to use GROUP BY to retrieve a result set with priority on alphabeticization

優先不過我對付CASE語句和使用MAX(CASE statement)語法不正確。

SELECT id, 
CASE 
    WHEN filename LIKE '%.mp3' THEN 'song' 
    ELSE 'other' END as type 
FROM filenames 

1 song 
2 song 
2 other 
3 other 
3 song 

SELECT id, 
CASE 
    WHEN filename LIKE '%.mp3' THEN 'song' 
    ELSE 'other' END as type 
FROM filenames 
GROUP BY id; 

1 song 
2 song 
3 other 

如何我會優先考慮type場對於那些來按字母順序持續多久?防爆。結果集應該是

1 song 
2 song 
3 song 

我想避免嵌套語句,如果可能的話。這可以通過MAX(type)語法完成嗎?

+1

我相信'MAX(CASE ...)AS sth'是確定的,至少最近使用的MySQL版本,什麼是您的錯誤信息? – piotrm 2012-04-25 11:35:31

+0

我的不好,我做了'MAX(CASE ... AS STH)'而不是'MAX(CASE ...)as sth' – user784637 2012-04-25 11:50:51

回答

0

您可以使用下面

SELECT id, 
CASE 
    WHEN filename LIKE '%.mp3' THEN 'song' 
    ELSE 'other' END as type 
FROM filenames 
GROUP BY id DESC; 

DESC會給你降序