sql—如何将select语句中的值添加为新列

jdg4fx2g  于 2021-08-01  发布在  Java
关注(0)|答案(3)|浏览(811)

我的table是空的

ID  FirstName   LastName    ReportsTo       Position    Age
8   Ashley      Johnson     null            Intern      25  
5   Noah        Fritz       Jenny Richards  Assistant   30  
6   David       S           Jenny Richards  Director    32  
3   Jenny       Richards    null            CEO         45

我想在上面的表中添加一列作为“boss title”,其值来自下面的select语句。但它不起作用。

SELECT *,
    case when ReportsTo='Jenny Richards' then 'CEO'
    else 'None' end 
    as 'Boss Title'
    FROM maintable_L8MOQ where ReportsTo='Jenny Richards' or ReportsTo is null order by age;
qnyhuwrf

qnyhuwrf1#

使用双引号 " 在新列名周围。这是工作演示。

SELECT *,
    case when ReportsTo='Jenny Richards' then 'CEO'
    else 'None' end 
    as "Boss Title"
FROM maintable_L8MOQ 
where ReportsTo='Jenny Richards' or ReportsTo is null 
order by age;
tyg4sfes

tyg4sfes2#

您可以自联接表或使用相关子查询来获取每个员工的老板的头衔。
但是,请注意,您的模式没有为此进行适当的优化。你应该引用 id 而不是它的名字:这将是更有效的(它避免了字符串串联的需要)和更准确的(没有风险的谐音)。
对于您当前的模式,这将是:

select l.*, coalesce(b.title, 'None') boss_title
from maintable_L8MOQ l
left join maintable_L8MOQ b 
    on concat(b.firstName, ' ', b.lastName) = l.reportsTo
order by l.age
eagi6jfj

eagi6jfj3#

select FirstName,LastName,ReportsTO,Position,Age
      ,(case when ReportsTO='Jenny Richards' then 'CEO' 
             when ReportsTO is null then 'None' 
        else 'None' 
        end) as "Boss Title"
from maintable_H9LYD
where   ReportsTO = 'Jenny Richards' 
     or ReportsTO is null
order by age ASC

相关问题