SQL Server嵌入式CASE语句

时间:2018-09-28 21:13:47

标签: sql-server tsql

如何在要获取最后一个值的地方编写查询?

例如,我有一个带有任务的表,每个父工作流程有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

2 个答案:

答案 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;

注意:

  • 我们正在使用ttde之类的别名来缩短代码
  • 我们摆脱了您最初的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