2011-11-18 72 views

回答

14

是的。但值被存儲爲文本,因此您必須先將它們轉換爲適當的數據類型。因此,以英寸爲單位的高度總和存儲在「其他」列中的hstore中

CREATE TABLE my_table (
    id integer primary key, 
    other hstore 
); 
insert into my_table values 
(1, hstore('height_in', '72') || hstore('weight_lbs', '180')), 
(2, hstore('height_in', '65') || hstore('girth_in', '42')); 

select sum((other->'height_in')::integer) sum_of_height 
from my_table; 

sum_of_height 
-- 
137 
+0

如果任何一行包含無法用整數轉換的值,該怎麼辦?它會給'錯誤:無效輸入語法爲整數:'所以如何獲得所需的結果跳過該行? – RockStar

+0

@RockStar:使用WHERE子句和正則表達式:'where(other - >'height_in')〜'^ \ d + $''。儘管如此,需要做到這一點指向應用程序代碼中的錯誤。修復。 –

相關問題