如何在SQL Server中的运行时添加额外的列

时间:2014-06-06 11:55:53

标签: sql-server

我的查询是

SELECT  
   RemainingQty, CompletedQty 
FROM 
   tblJobStatus AS JT 
LEFT OUTER JOIN 
   TBLJOBWORKS  AS TJ ON JobWorksId = TaskId 
LEFT OUTER JOIN 
   tblTotalJob AS T ON T.Id = JobID    
WHERE 
   JT.ProductID = '28' 
   AND ItemId = '15' 
ORDER BY 
   JobSequence ASC

执行查询时,我得到了这个结果

enter image description here

现在我想在运行时添加一个额外的列,其中包含状态。如果RemainingQty为0且CompletedQty大于0,则状态列将包含完整的其他待处理项。

如下图所示

enter image description here

没有循环可以吗?

4 个答案:

答案 0 :(得分:2)

当然,没问题 - 这是一个非常简单的CASE表达式:

SELECT  
   RemainingQty, CompletedQty,
   Status = CASE
               WHEN RemainingQy = 0 AND CompletedQty > 0
                 THEN 'Complete'
                 ELSE 'Pending'
            END
FROM 
   tblJobStatus AS JT 
LEFT OUTER JOIN 
   TBLJOBWORKS  AS TJ ON JobWorksId = TaskId 
LEFT OUTER JOIN 
   tblTotalJob AS T ON T.Id = JobID    
WHERE 
   JT.ProductID = '28' 
   AND ItemId = '15' 
ORDER BY 
   JobSequence ASC

答案 1 :(得分:1)

select
    ...,
    case
       when RemainingQty = 0 and CompletedQty > 0 then 'Complete'
       else 'Pending'
    end as Status
from ...

答案 2 :(得分:1)

SELECT  
   RemainingQty, CompletedQty,
   case when RamaininQty = and CompletedQty > 0 then 'Complete' else 'Pending' end as Status
FROM 
   tblJobStatus AS JT 
LEFT OUTER JOIN 
   TBLJOBWORKS  AS TJ ON JobWorksId = TaskId 
LEFT OUTER JOIN 
   tblTotalJob AS T ON T.Id = JobID    
WHERE 
   JT.ProductID = '28' 
   AND ItemId = '15' 
ORDER BY 
   JobSequence ASC

答案 3 :(得分:1)

SELECT  
   RemainingQty, CompletedQty,
   Case when RemainingQty=0 and  CompletedQty>0 then 'Complete' else 'Pending' end as Status
FROM 
   tblJobStatus AS JT 
LEFT OUTER JOIN 
   TBLJOBWORKS  AS TJ ON JobWorksId = TaskId 
LEFT OUTER JOIN 
   tblTotalJob AS T ON T.Id = JobID    
WHERE 
   JT.ProductID = '28' 
   AND ItemId = '15' 
ORDER BY 
   JobSequence ASC