将输出行文本替换为其他文本,而无需更新或插入

时间:2018-09-25 10:41:25

标签: sql postgresql

我有一个如下查询:

SELECT 
    x.ans, 
    COUNT(*) AS num_ans
FROM 
    ans x, 
    get_fit('5')
GROUP BY 
    x.ans, 
    get_fit.getfit
ORDER BY 
    x.ans ASC;

输出:

  id | num_ans
 ----+---------------
  X  |  5
  Z  |  7

但是我想分别用AName和BName更改X和Z,而不插入或更新表。我该怎么办?

1 个答案:

答案 0 :(得分:0)

一种实现此目的的方法是CASE命令。您的查询可能如下所示:

SELECT 
    x.ans as original_id,
    CASE WHEN x.ans='X' THEN 'AName'
         WHEN x.ans='Z' THEN 'BName'
         ELSE x.ans
    END as modified_id,
    COUNT(*) AS num_ans
FROM 
    ans x, 
    get_fit('5')
GROUP BY 
    x.ans, get_fit.getfit
ORDER BY 
    x.ans ASC;