我有2列名为Debit
和Credit
。我想从一列中获取值并放入第三列Balance
。我想应用一个条件,如果Debit
包含任何值,则应将其放在Balance
列中,如果Credit
有某些内容,则应将该值插入列中,但如果两者都有一些值,那么只有一个值应该去Debit
或Credit
。
Debit Credit Balance
------------------------------
1000 NULL 1000
2200 NULL 2200
NULL 3000 3000
1500 1500 1500
查询:
SELECT
Debit, Credit, SUM(Credit|Debit) AS Balance
FROM Table
答案 0 :(得分:5)
例如COALESCE()
就足够了
SELECT Debit, Credit, COALESCE(Credit, Debit) AS Balance
FROM Table
答案 1 :(得分:2)
如果我理解正确,你正在寻找类似的东西。
SELECT Debit, Credit,
(
CASE WHEN Credit IS NOT NULL THEN Credit
ELSE Debit
END
) AS Balance
FROM [Table]
答案 2 :(得分:2)
declare @tab table(Debit int,Credit int)
insert into @tab
select 1000 , NULL
union all
select 2200 , NULL
union all
select NULL , 3000
union all
select 1500 , 1500
SELECT Debit, Credit,
CASE WHEN Debit is null then Credit
WHEN Credit is null then Debit else Debit end AS Balance
FROM @tab
输出
Debit Credit Balance
1000 NULL 1000
2200 NULL 2200
NULL 3000 3000
1500 1500 1500