我有一个专栏
--------------------------------------------------------------
| Sl. No. | bal1 | bal2 | bal3 | status1 | status2 | status3 |
--------------------------------------------------------------
| 1 | 520 | 270 | 351 | 1 | 0 | 1 |
| 2 | 201 | 456 | 154 | 0 | 1 | 1 |
--------------------------------------------------------------
我想在SQL Server
中为Status value = 1添加rows字段例如。结果
--------------------
| 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
--------------------
提前致谢。
答案 0 :(得分:3)
如果status
值始终为1或0,则可以乘以并添加:
select [Sl. No.], bal1 * status1 + bal2 * status2 + bal3 * status3
from table
答案 1 :(得分:2)
你可以使用CASE
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
答案 2 :(得分: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