如何编写case when语句以查看2个值的和是否相等?

时间:2019-04-25 18:01:47

标签: sql

我仍在学习sql,因此如果这很简单,我深表歉意。

我需要sql代码来对销售金额求和,对returnamount求和,如果它们相等,我想用1标记该帐号以知道它已被完全取消。

i.[status], i.accountnumber,
case when sum(i.saleamount) = sum(r.returnamount) then 1 else 0 end as full_return_flag
from [idtable] i 
join [returntable] r on r.id = i.id


> Account Number Sale Amount  Return Amount   Full_return_flag  Status
> 1                 500              250                    1    Open
> 2                 500             1500                    1    Open
> 3                2000               0                     0    Neutral
> 4                  100              0                     0    Closed

2 个答案:

答案 0 :(得分:0)

您要使用case表达式进行聚合:

select i.status, i.accountnumber, sum(i.saleamount) as saleamount, sum(r.returnamount) as returnamount,
       (case when sum(i.saleamount - r.returnamount) = 0 then 1 else 0 end) as Full_return_flag
from idtable] i inner join
     returntable r
     on r.id = t.id
group by i.status, i.accountnumber;

答案 1 :(得分:0)

您需要完整的查询:

select i.accountnumber,
       sum(i.saleamount) as sale_amount, sum(r.returnamount) as return_amount,
       (case when sum(i.saleamount) = sum(r.returnamount) then 1 else 0 end) as full_return_flag
from [idtable] i left join
     [returntable] r
     on r.id = i.id
group by i.accountnumber;

status不在结果集中,因此我认为查询中不需要它。但是您可以根据需要将其同时包含在selectgroup by中。