Select 基于另一列值的动态列?

Select dynamic column based on value of another column?

鉴于以下 table,我想根据 WhichName 列的值动态 select Name1Name2 字段。

id  Name1   Name2   WhichName   SomeValue
1   Bob     James   1           Blue
2           Steve   2           Horse
3   Fred            1           Radish

结果应如下所示:

id  Name    SomeValue
1   Bob     Blue
2   Steve   Horse
3   Fred    Radish

DBMS 是 Caché

你可以用 case:

select id,
       (case when WhichName = 1 then Name1 else Name2 end) as Name,
       SomeValue
from <table>;

注意:如果你喜欢Name1,除非是NULL,那么你可以使用COALESCE():

select id, coalesce(Name1, Name2) as Name, SomeValue
from <table>;