在sql中根据需要显示列值

时间:2017-12-29 12:29:40

标签: sql sql-server

如果我有一个列,其中出现十位数值,如Column A = 11111000那么如何在sql中显示此值(如List,Add,Edit,Delete,Export)。

有条件意味着如果第一个位置有1则显示List,如果第二个位置有1则显示Add,第三个位置有1然后是Edit,第四个位置有1然后是Delete,第五个位置有1然后是Export。

2 个答案:

答案 0 :(得分:0)

如果值是字符串,则可以执行以下操作:

select stuff( ((case when substring(a, 1, 1) = 1 then ',List' else '' end) +
               (case when substring(a, 2, 1) = 1 then ',Add' else '' end) +
               . . .
              ), 1, 1, '')

按位运算符的逻辑类似:

select stuff( ((case when a & 2^9 then ',List' else '' end) +
               (case when 2 & 2^8 then ',Add' else '' end) +
               . . .
              ), 1, 1, '')

答案 1 :(得分:0)

也许Substring函数可以帮助您识别这些值

select 
    id, ColumnA,
    case when substring(ColumnA,1,1) = '1' then 'X' end as List,
    case when substring(ColumnA,2,1) = '1' then 'X' end as [Add],
    case when substring(ColumnA,3,1) = '1' then 'X' end as Edit,
    case when substring(ColumnA,4,1) = '1' then 'X' end as [Delete],
    case when substring(ColumnA,5,1) = '1' then 'X' end as [Export]
from Table1

enter image description here

我根据评论

更新查询
select 
    id, ColumnA,
    stuff(
    case when substring(ColumnA,1,1) = '1' then ',List' else '' end +
    case when substring(ColumnA,2,1) = '1' then ',Add' else '' end +
    case when substring(ColumnA,3,1) = '1' then ',Edit' else '' end +
    case when substring(ColumnA,4,1) = '1' then ',Delete' else '' end +
    case when substring(ColumnA,5,1) = '1' then ',Export' else '' end
    ,1,1,''
    )
from Table1

enter image description here