如何在要获取最后一个值的地方编写查询?
例如,我有一个带有任务的表,每个父工作流程有1-4个任务。 然后,我有一个完整的列,其值为1或0。
我想返回1个值,即任务1或2或3或4,具体取决于任务是否完成。
我尝试了嵌入式CASE语句,但是它总是返回值4。
必须有更好的方法。
SELECT
Estimate.EstimateID, Estimate.EstimateNo,
CASE
WHEN TransWorkFlow.OwnerID = Estimate.EstimateID
THEN
CASE
WHEN TransWorkFlowDetails.TaskNo = 1 AND TransWorkFlowDetails.Completed = 0
THEN 1
ELSE
CASE
WHEN TransWorkFlowDetails.TaskNo = 2 AND TransWorkFlowDetails.Completed = 0
THEN 2
ELSE
CASE
WHEN TransWorkFlowDetails.TaskNo = 3 AND TransWorkFlowDetails.Completed = 0
THEN 3
ELSE
CASE
WHEN TransWorkFlowDetails.TaskNo = 4 AND TransWorkFlowDetails.Completed = 0
THEN 4
ELSE 4
END
END
END
END
END AS TaskCompleted
FROM
TransWorkFlow
INNER JOIN
TransWorkFlowDetails ON TransWorkFlow.TransWorkFlowID = TransWorkFlowDetails.TransWorkFlowID
INNER JOIN
Estimate ON TransWorkFlow.OwnerID = Estimate.EstimateID
答案 0 :(得分:2)
似乎可以将其简化为一个简单的CASE
语句
SELECT
e.EstimateID,
e.EstimateNo,
CASE WHEN td.Completed = 0 AND td.TaskNo IN (1,2,3,4) THEN td.TaskNo ELSE 4 END AS TaskCompleted
FROM TransWorkFlow t
INNER JOIN TransWorkFlowDetails td ON t.TransWorkFlowID = td.TransWorkFlowID
INNER JOIN Estimate e ON t.OwnerID = e.EstimateID;
注意:
t
,td
和e
之类的别名来缩短代码CASE
支票,因为INNER JOIN
覆盖了该支票TaskNo
似乎是您的检查条件,也是您的输出条件,我们可以在THEN
部分中引用它答案 1 :(得分:1)
不太清楚您要在这里做什么,但是我认为可以简化这种情况。
case when TransWorkFlowDetails.Completed = 0
AND TransWorkFlowDetails.TaskNo in (1, 2, 3, 4)
THEN TransWorkFlowDetails.TaskNo
ELSE
--whatever you want here
END