我从使用嵌套If语句的同事那里继承了一个电子表格,如下所示:
=IF(AND([@[Pred Type]]="PR_FS",[@[ST Finish]]="A"),
0,
IF(AND([@[Pred Type]]="PR_SS", OR([@[ACT_START_DATE]]<>0,[@[ST Start]]="A")),
0,
IF(AND([@[Pred Type]]="PR_SF",OR([@[ACT_START_DATE]]<>0,[@[ST Start]]="A")),
0,
IF(AND([@[Pred Type]]="PR_FF",[@[STFinish]]="A"),0,1)
)
)
)
我知道我可以编写一个CASE语句来模仿它,但无法弄清楚它的语法。我试过了:
,CASE WHEN #Preds.Pred_Type = 'PR_FS' and #Tbl_Sched_Act.Expected_Finish = 'A' THEN 0
WHEN #Preds.Pred_Type = 'PR_SS' OR ACT_START_DATE IS NOT NULL OR Start_RAW IS NOT NULL THEN 0
WHEN #Preds.Pred_Type = 'PR_SF'OR ACT_START_DATE IS NOT NULL OR Start_RAW IS NOT NULL THEN 0
WHEN #Preds.Pred_Type = 'PR_FF' and #Tbl_Sched_Act.Expected_Finish = 'A' THEN 0
ELSE 1
END as PRED_MET
但是,CASE语句不会将任何项目评估为等于1.它们都评估为0,这是不正确的。
有没有人知道如何正确编写我的CASE声明?
答案 0 :(得分:1)
您需要将括号()
内的CASE
WHEN #Preds.Pred_Type = 'PR_FS' and #Tbl_Sched_Act.Expected_Finish = 'A'
THEN 0
WHEN #Preds.Pred_Type = 'PR_SS'
AND (ACT_START_DATE <> 0 OR Start_RAW <> 0)
THEN 0
WHEN #Preds.Pred_Type = 'PR_SF'
AND (ACT_START_DATE <> 0 OR Start_RAW <> 0)
THEN 0
WHEN #Preds.Pred_Type = 'PR_FF' and #Tbl_Sched_Act.Expected_Finish = 'A'
THEN 0
ELSE 1
END as PRED_MET
分组以强制运算符优先。
<> 0
注意: :如果数字为NOT NULL
,那么CASE
WHEN #Tbl_Sched_Act.Expected_Finish = 'A'
AND #Preds.Pred_Type IN ('PR_FS', 'PR_FF')
THEN 0
WHEN (ACT_START_DATE <> 0 OR Start_RAW <> 0)
AND (#Preds.Pred_Type IN ('PR_SS','PR_SF')
THEN 0
ELSE 1
END as PRED_MET
DEMO
但这也可以简化为:
select users.name as name,cu.*,ca.*
from users
left join (
select created_by,
sum(CASE WHEN amount > 0 THEN amount END) as current_positive,
sum(CASE WHEN amount < 0 THEN amount END) as current_negative
from current_transaction
where created_at between :start_date and :end_date
group by created_by
) cu on users.id = cu.created_by
left join (
select created_by,
sum(CASE WHEN amount > 0 THEN amount END) as cash_positive,
sum(CASE WHEN amount < 0 THEN amount END) as cash_negative
from cash_transaction
where created_at between :start_date and :end_date
group by created_by
) ca on users.id = ca.created_by
where users.type = 3