2013-03-19 110 views
4

所以我有,目前返回1和0的表像下SQL和條件邏輯

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

不過,我想修改我的查詢,查詢,以便與多個1S行,我們只保持行中的第一個1。例如,我想將(1 1 1)轉換爲(1 0 0),(0 1 1)轉換爲(0 1 0),等等。 IF邏輯似乎是最後的手段。

你會推薦什麼?我可以做一個case語句,其中一列中的值取決於另一列值嗎?

換句話說,「COLUMN 2 = CASE WHEN COLUMN 1 = 1且COLUMN 2 = 1,那麼0 ...等等?」

+2

請註明您是通過添加適當的標籤針對RDBMS(甲骨文,SQL服務器,MySQL的,等等)。可能會有利用不被普遍支持的語言或產品功能的答案。此外,通過使用特定的RDBMS標記它,您的問題可能會得到更適合回答的人的關注 – Taryn 2013-03-19 15:58:30

回答

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 
0

作爲替代條件結構,你可以做些什麼如:

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

這確實取決於列a,b和c每個允許值0和1只。

(例here