【问题标题】:How to add actual column name as alias name in a Case Expression如何在案例表达式中添加实际列名作为别名
【发布时间】:2020-06-30 12:59:38
【问题描述】:

我在 PostgreSQL 10 中有一个表,其中有几列 boolean 类型。在选择查询中,我想将值转换为 1/0 而不是 t/f,对于空白值,请将其保留为空白。

尝试了 boolean_col::int 语法,但仍然没有强制转换。根据 Postgres Doc 的原因,

布尔类型的值不能直接转换为其他类型(例如,CAST(布尔值 AS 整数)不起作用)。这可以使用 CASE 表达式来完成:CASE WHEN boolval THEN 'value if true' ELSE 'value if false' END。

所以尝试使用大小写表达式,得到了预期的结果,但现在列名打印为大小写我想要打印实际列名,因此使用别名语法,但这只有在我提供除实际列名之外的任何内容并且我想打印时才有效别名与实际列名相同。

SELECT
 (case when column1 then 1 else 0 end) as "column1" ,(case when column1 then '' else '' end ) as "column1" 
 ,(case when column2 then 1 else 0 end) as "column2" , (case when column2 then '' else '' end) as "column2"
FROM tablename 

实际结果:

Case  Case
1      0
       1
0      

预期结果:

column1    column2
1           0
            1
0           

【问题讨论】:

  • 这不是真的。您的查询将使用column1column2 作为别名。
  • boolean_col::int 工作正常:dbfiddle.uk/…
  • 您引用的是 8.0 或更早版本的文档。那是很久以前的事了。

标签: postgresql


【解决方案1】:

你应该使用:

(case when column1 then 1 else 0 end as "column1")

【讨论】:

  • 失败并出现错误:“as”处或附近的语法错误
  • 去掉无用的括号
【解决方案2】:

我没看到:

create table bool_test (column1 bool, column2 bool);
CREATE TABLE
insert into bool_test values ('t', 'f'), ('f', 'f'), ('t', 't');

SELECT
 (case when column1 then 1 else 0 end) as "column1" ,(case when column1 then '' else '' end ) as "column1" 
 ,(case when column2 then 1 else 0 end) as "column2" , (case when column2 then '' else '' end) as "column2"
FROM bool_test;

 column1 | column1 | column2 | column2 
---------+---------+---------+---------
       1 |         |       0 | 
       0 |         |       0 | 
       1 |         |       1 | 
(3 rows)

一定有其他事情你没有告诉我们。

【讨论】:

    【解决方案3】:

    感谢大家的宝贵意见。我正在使用的查询和你们中的一些人共享的查询是有效的,问题出在客户端工具 (IDE) 中,我之前使用的是 DBeaver 工具,但不知何故没有给出预期的结果。但后来我在另一个工具 Heidisql 中尝试了相同的查询,它给出了实际结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 2017-02-05
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      相关资源
      最近更新 更多