带条件逻辑的SQL

时间:2013-03-19 15:57:01

标签: sql sql-server

所以我有一个查询,当前返回一个1s和0s的表,如下所示

1 0 0
1 1 0
0 0 1
0 1 1
1 1 0
1 1 1

但是,我想修改我的查询,以便对于具有多个1的行,我们只保留行中的第一个1。例如,我想将(1 1 1)转换为(1 0 0),(0 1 1)转换为(0 1 0),依此类推。似乎IF逻辑将是最后的手段。

你们都推荐什么?我可以做一个case语句,其中一列中的值取决于另一列值吗?

换句话说,“第2列=当列1 = 1且第2列= 1,然后是0 ......等等时的情况?”

2 个答案:

答案 0 :(得分:2)

对于三列,逻辑是:

select col1,
       (case when col1 = 1 then 0 else col2 end) as col2,
       (case when col1 = 1 or col2 = 1 then 0 else col3 end) as col3
from query q

如果您有更多列,我会采用不同的方法:

select col1,
       (case when firstOne < 2 then 0 else col2 end) as col2,
       (case when firstOne < 3 then 0 else col3 end) as col3,
       (case when firstOne < 4 then 0 else col4 end) as col4,
       . . .
from (select q.*,
             (case when col1 = 1 then 1
                   when col2 = 1 then 2
                   when col3 = 1 then 3
                   . . .
              end) as FirstOne
      from query q
     ) q

答案 1 :(得分:0)

作为条件结构的替代方法,您可以执行以下操作:

select a, b * (1-a) as [b'], c * (1-b) * (1-a) as [c'] 
from your_table

这取决于列a,b和c,每个只允许值0和1。

(示例here。)

相关问题