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

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

我的table是空的

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

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

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

qnyhuwrf1#

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

  1. SELECT *,
  2. case when ReportsTo='Jenny Richards' then 'CEO'
  3. else 'None' end
  4. as "Boss Title"
  5. FROM maintable_L8MOQ
  6. where ReportsTo='Jenny Richards' or ReportsTo is null
  7. order by age;
tyg4sfes

tyg4sfes2#

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

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

eagi6jfj3#

  1. select FirstName,LastName,ReportsTO,Position,Age
  2. ,(case when ReportsTO='Jenny Richards' then 'CEO'
  3. when ReportsTO is null then 'None'
  4. else 'None'
  5. end) as "Boss Title"
  6. from maintable_H9LYD
  7. where ReportsTO = 'Jenny Richards'
  8. or ReportsTO is null
  9. order by age ASC

相关问题