SQL 条件列选择

SQL Conditional Column selection

我是运行一个简单的查询:

 Select "ID", "Original_ID" from table;

这让我明白了:

ID       |  Original_ID  
56917659 |  #56906230  Captain  
56781961 |  #56754164 Shipment Management   
56794542 |  #56620028 Team Member  
56655028 |  #50817965 Commercial Owner  
56258156 |  Process Expert                                         
55780912 |  Process Expert    

然后我可以使用这个:

select "ID", substr("Original_ID",2,8)as "Original_ID" from table;  


ID       | Original_ID  
56917659 |  56906230  
56781961 |  56754164  
56794542 |  56620028  
56655028 |  50817965  
56258156 |  rocess E  
55780912 |  rocess E  

我需要的是第 3 列 "True_ID",它显示 substr("Original_ID",2,8)as "True_ID" 但仅当 "Original_ID" 以 '# ' 如果不只是显示 "ID" 中的值。我正在使用 dashDB。

CASE WHEN判断Original_ID的第一个字符是否为#:

select 
   ID
   , substr(Original_ID,2,8) as Original_ID
   , CASE WHEN substr(Original_ID, 1, 1) = '#' 
          THEN substr(Original_ID, 2, 8) 
          ELSE 'ID' END as True_ID
from table;

您可以简单地在 CASE 中使用 LEFT 函数完成:

SELECT
   ID,
   SUBSTR(Original_ID,2,8) as Original_ID,
   CASE WHEN LEFT(Original_ID, 1) = '#' 
      THEN SUBSTR(Original_ID, 2, 8) 
      ELSE ID
   END AS True_ID
FROM table;