如何在postgresql中添加基于其他列的列

时间:2016-03-11 16:54:33

标签: postgresql

我想要一个名为" newname"的列。根据postgresql中的sql查询填充具有不同名称的字符串。

IF fullstate='California' and county in (71 65) THEN newname='TEMECULA'; 
IF fullstate='California' and county in (27 51) THEN newname='SHIPROCK'; 
IF fullstate='California' and county in (29 107 19 31 53 79 83 111 37 39 69) THEN newname='TULE'; 
IF fullstate='California' and county in (25) THEN newname='PHOENIX'; 
IF fullstate='California' and county in (59) THEN newname='LOS ANGELES';
IF fullstate='California' and county in (73) THEN newname='ORANGE'; 
IF fullstate='California' and county in (41 13 1 81 87 85 75) THEN newname='YERBA BUENA';

" newname"列基于另外两列创建" fullstate"和"县"。我是postgresql的新手,无法弄清楚我是否需​​要一个函数或一个CASE WHEN语句来使这个查询起作用。

1 个答案:

答案 0 :(得分:0)

case表达式可以帮到你:

CASE    
WHEN fullstate = 'California' AND county IN (71, 65) THEN 'TEMECULA'
WHEN fullstate = 'California' AND county IN (27, 51) THEN 'SHIPROCK'
WHEN fullstate = 'California' AND county IN (29, 107, 19, 31, 53, 79, 83, 111, 37, 39, 69) THEN 'TULE'
WHEN fullstate = 'California' AND county IN (25) THEN 'PHOENIX'
WHEN fullstate = 'California' AND county IN (59) THEN 'LOS ANGELES'
WHEN fullstate = 'California' AND county IN (73) THEN 'ORANGE'
WHEN fullstate = 'California' AND county IN (41, 13, 1, 81, 87, 85, 75) THEN 'YERBA BUENA'
END AS newname