2014-10-20 60 views
1

我有一列SQL服務器:有條件地添加行和列

-------------------------------------------------------------- 
| Sl. No. | bal1 | bal2 | bal3 | status1 | status2 | status3 | 
-------------------------------------------------------------- 
| 1 | 520 | 270 | 351 | 1 | 0  | 1 | 
| 2 | 201 | 456 | 154 | 0 | 1  | 1 | 
-------------------------------------------------------------- 

我想補充的行字段狀態值= 1在SQL Server

如。結果

-------------------- 
| Sl. No. | amount | 
-------------------- 
| 1 | 871 | // bal1 + bal3 as the status1 and status3 is 1 
| 2 | 610 | // bal2 + bal3 as the status2 and status3 is 1 
-------------------- 

在此先感謝。

+1

'CASE status1當1那麼bal1 ELSE 0 END + CASE狀態2當1那麼bal2 ELSE 0 END + CASE狀態3當1 TH EN bal3 ELSE 0 END' – 2014-10-20 03:36:05

回答

2

您可以使用CASE

SQL Fiddle

SELECT [SI. No.], 
     (case when status1 =1 then bal1 else 0 end + 
     case when status2 =1 then bal2 else 0 end + 
     case when status3 =1 then bal3 else 0 end) as balance 

from Table1 
3

做到這一點。如果status值永遠是1或0,你可以乘法和加法:

select [Sl. No.], bal1 * status1 + bal2 * status2 + bal3 * status3 
from table 
+1

聰明的想法!對你很好@adrift – sqluser 2014-10-20 04:36:53

+0

對downvote很好奇。這將提供與多個病例報告相同的結果,並且我預計會更好。 – 2014-10-20 14:02:17

+0

不是我,但你有任何證據表明這會表現更好嗎?即使它確實存在,是否證明了這種含糊不清和不完全自我記錄的方法呢?如果狀態列更改爲不同類型(如CHAR(1)以支持「Y'' /''N''或TINYINT以支持其他狀態類型),會發生什麼情況? – 2014-10-21 01:59:16

2
SELECT [Sl. No.], 
    (case when bs.[status1] =1 then bs.bal1 else 0 end + 
    case when bs.status2 =1 then bs.bal2 else 0 end + 
    case when bs.status3 =1 then bs.bal3 else 0 end) as amount 
from BalStatus AS bs