2012-10-10 39 views
2

由字母顯示由我已經形成了這樣的數據庫:由非字母排序,但在由/順序組中的PostgreSQL

descr | hours | timer  
----------+-------+------------ 
foo  | 1.3 | 2012-07-14 
foo  | 2.5 | 2012-07-15 
foo  | 2.35 | 2012-07-16 
bar  |  1 | 2012-08-16 
baz  |  1 | 2012-08-16 
buh  |  5 | 2012-08-17 

這做什麼,我希望:

abc=# select extract('month' from timer) as Month, sum(hours) from foo group by Month  order by 1; 

month | sum 
------+------ 
7  | 6.15 
8  | 7 

這並未「T相當做什麼,我希望:

abc=# select to_char(timer, 'Month'), sum(hours) from foo group by 1 order by 1 asc; 

to_char | sum 
----------+------ 
August | 7 
July  | 6.15 

期望的結果是:

month  | sum 
----------+----- 
July  | 6.15 
August | 7 

我明白爲什麼事情正在#3中發生,但是如何以最有效的方式在PostgreSQL中實現預期的結果?

+1

爲什麼不在''order by''關鍵字中使用'extract('timer')? –

+0

我想要的是月份名稱(按實際月份排序,而不是按字母順序排列)。只提取似乎給我的月份的數字部分。查看所需的結果(上次代碼粘貼)。 – Arima

回答

4

可以在ORDER BY部分使用提取的表達:

SELECT to_char(timer, 'Month'), SUM(hours) 
FROM foo 
GROUP BY to_char(timer, 'Month'), extract('Month' from timer) 
ORDER BY extract('Month' from timer) ASC; 

此查詢不期望的結果。