2010-10-11 51 views
1

繼最近回答的問題,我有以下代碼:MySQL的訂購查詢 - 進一步的問題

SELECT q21coding, COUNT(q21coding) AS Count 
FROM  tresults_acme 
WHERE q21 IS NOT NULL AND q21 <> '' 
GROUP BY q21coding 
ORDER BY IF(q21coding = 'Other', 1, 0) ASC, Count DESC 

它帶回了以下內容:

q21coding         Count 
Difficulty in navigating/finding content  53 
Positive comments       28 
Suggestions for improvement     14 
Inappropriate content/use     13 
Improve search facility      6 
Include information about staff and teams  5 
Content needs updating      4 
Other          30 

你會發現,其他是現在在底部 - 但是,有沒有辦法確保積極評論和其他總是底部兩個(與底部的其他)無論計數大小?

感謝,

荷馬

回答

2

其實沒有必要在原來的查詢中使用IF(q21coding = 'Other', 1, 0)。在MySQL中,你可以使用任何表達的ORDER BY caluse和q21coding = 'Other'就足夠了:

... ORDER BY q21coding = 'Other', Count DESC 

q21coding = 'Other'表達式,如果假返回1如果爲true,或0。這將把q21coding = 'Other'的行放在最下面。

,你需要做的有「積極評價」和什麼「其他」無論是在底部是這樣的:

... ORDER BY q21coding = 'Other', q21coding = 'Positive comments', Count DESC 

基本測試用例:

CREATE TABLE my_table (id int, q21coding varchar(100), count int); 

INSERT INTO my_table VALUES (1, 'Inappropriate content/use', 13); 
INSERT INTO my_table VALUES (2, 'Other', 30); 
INSERT INTO my_table VALUES (3, 'Difficulty in navigating/finding content', 53); 
INSERT INTO my_table VALUES (4, 'Positive comments', 28); 
INSERT INTO my_table VALUES (5, 'Improve search facility', 6); 
INSERT INTO my_table VALUES (6, 'Content needs updating', 4); 
INSERT INTO my_table VALUES (7, 'Suggestions for improvement', 14); 
INSERT INTO my_table VALUES (8, 'Include information about staff and teams', 5); 

結果:

SELECT q21coding, count 
FROM  my_table 
ORDER BY q21coding = 'Other', q21coding = 'Positive comments', Count DESC; 

+-------------------------------------------+-------+ 
| q21coding         | count | 
+-------------------------------------------+-------+ 
| Difficulty in navigating/finding content | 53 | 
| Suggestions for improvement    | 14 | 
| Inappropriate content/use     | 13 | 
| Improve search facility     |  6 | 
| Include information about staff and teams |  5 | 
| Content needs updating     |  4 | 
| Positive comments       | 28 | 
| Other          | 30 | 
+-------------------------------------------+-------+ 
8 rows in set (0.00 sec)