在SQL中选择一个带虚拟值的虚拟列?

kal*_*kal 35 sql

我有一张桌子,内容如下

Table1
col1   col2
------------
 1      A 
 2      B
 3      C
 0      D
Run Code Online (Sandbox Code Playgroud)

结果

col1   col2  col3
------------------
0       D     ABC
Run Code Online (Sandbox Code Playgroud)

我不知道如何编写查询,可以选择col1和col2

select col1, col2 from Table1 where col1 = 0;
Run Code Online (Sandbox Code Playgroud)

我该如何添加值为ABC的col3.

And*_*are 85

试试这个:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;
Run Code Online (Sandbox Code Playgroud)

  • 如何在PostgreSQL中执行此操作? (2认同)

Ale*_* N. 12

如果你的意思是ABC只是简单的价值,那么上面的答案就是可行的.

如果您想要连接主查询未选择的行值,则需要使用子查询.

这样的事情可能有用:

SELECT t1.col1, 
t1.col2, 
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM  Table1 t2 WHERE t2.col1 != 0) as col3 
FROM Table1 t1
WHERE t1.col1 = 0;
Run Code Online (Sandbox Code Playgroud)

实际语法可能有点偏