select amount,sid,
CASE
WHEN force_status=1 THEN select sum(amount) as amount,sid FROM(select amount-force_amount as amount,sid from lease_order WHERE force_status=1 and `sid` IN (7,19)) as temp GROUP BY sid
else 0 end as amount
from order;
我有一个表order
,当字段force_status=1
时则使用force_amount-amount
差额进行累加,并对sid
进行分组统计,当字段force_status!=1
,则使用amount
统计并sid
分组。
如果我单独执行
select sum(amount) as amount,sid FROM(select amount-force_amount as amount,sid from order WHERE force_status=1 and `sid` IN (7,19)) as temp GROUP BY sid
则没有问题,会显示如下信息
amount sid
1.04 7
0.03 19
当使用CASE WHEN
则报错,望大神能帮我抽空看看是哪里出问题了。最终效果需要实现成
amount sid
2.03 8
0.03 19
8.03 31
9.13 20
这样效果
1
c6h6benzene 2020-12-05 02:54:09 +08:00
sum (case when force_status=1 then force_amount-amount else amount) group by sid
|
2
c6h6benzene 2020-12-05 02:54:29 +08:00
(少了一个 end😅)
|
3
cs5117155 OP @c6h6benzene 还是不知道怎么写😅,能把 CASE WHEN 也加上,写个详细的吗
|
4
c6h6benzene 2020-12-05 12:11:15 +08:00 via iPhone
@cs5117155 #3 就…其实不需要子查询。case when 可以写在 sum 里面的。
select sid, sum(case when force_status=1 then force_amount-amout else amount end) from order group by sid |
5
cs5117155 OP @c6h6benzene good,谢谢可以了,第一次写这个 case when 有点绕了
|