2016-10-14 30 views
0

我有一個7k記錄的PostgreSQL表。每個記錄有3個唯一的ID和3個字段。兒童保育,shcools,醫院。有所有整數字段。我想添加一個新列並計算每行的受體總數(學校,兒童保育,醫院)。我想這應該是非常簡單明瞭與添加在柱上,用一個選擇做一個插入,但我沒有得到我想要SQL將列添加在一起

alter table site add total integer; 

insert into site(total) select sum(schools+childcares+hospitals) as s from site; 

結果我也有試過一組由ID在插入select語句

回答

1

您正在尋找UpdateInsert

Update site 
set total = COALESCE(schools,0)+COALESCE(childcares,0)+COALESCE(hospitals,0) 

新增COALESCE處理NULL值。

例:

1 + 2 + NULL = NULL所以更換NULL0我用COALESCE

現在它將是1 + 2 + 0(NULL) = 3

+0

coalesce做什麼? – ziggy

+0

@ziggy - 'Coalesce'將從列表中返回第一個'Not Null'值。我用'zero'替換NULL值。 –

+0

ahh gotcha很好,工作! – ziggy