Sql查询将两列值乘以第三列

时间:2014-01-30 19:10:38

标签: sql sql-server

我想将两列值乘以第三列。这是我的疑问:

select distinct pr.PSProjectId,sfa.CodePattern, case when sfqd.NCR IS null then 'blank' else sfqd.NCR end as NCR  
,
case when sfqd.NCR !='blank' then 
(Select DATEDIFF(minute,starttime,EndTime) from ShopFloorStatusDetail where ShopFloorActivityId=sfa.ShopFloorActivityId
and StatusId=8
)
else 
DATEDIFF(MINUTE,sfs.ShiftStarTime,sfs.shiftendtime)
 end as timediff,
(select COUNT(1) from ShopFloorEmployeeTime where ShopFloorShiftId=sfs.ShopFloorShiftId) as totalemployee

from ShopFloor sf  
inner join Project pr on pr.ProjectId=sf.ProjectId  
inner join ShopFloorActivity sfa on sf.ShopFloorId=sfa.ShopFloorId  
inner join ShopFloorShift sfs on sfs.ShopFloorActivityId=sfa.ShopFloorActivityId  
left join ShopFloorStatusDetail sfsd on sfsd.ShopFloorActivityId=sfs.ShopFloorActivityId  
left join ShopFloorQCDetail sfqd on sfqd.ShopFloorStatusDetailId=sfsd.ShopFloorStatusDetailId  
and sfqd.NCR is not null  
where CAST(sfs.ShiftStarTime as DATE) between '2014/01/06' and '2014/01/07' 

并且此查询的输出为

PSProjectId    CodePattern  NCR   timediff  totalemployee
0000129495     3TMEU       blank        8              1
0000130583     3UA1P       blank        1              1
0000130583     3UA1P       blank       2090            2

现在我想将列timediff和totalemployee相乘并在新列中显示。

我该怎么做?请帮忙。

1 个答案:

答案 0 :(得分:0)

只需添加一个新列,将现有表达式相乘:

case when sfqd.NCR !='blank' 
     then (Select DATEDIFF(minute,starttime,EndTime) 
             from ShopFloorStatusDetail 
            where ShopFloorActivityId=sfa.ShopFloorActivityId
              and StatusId=8
           )
     else DATEDIFF(MINUTE,sfs.ShiftStarTime,sfs.shiftendtime)
 end 
*
(select COUNT(1) 
   from ShopFloorEmployeeTime 
  where ShopFloorShiftId=sfs.ShopFloorShiftId) 

或者,将整个现有查询包装在另一个查询中,并将计算列相乘:

select
    PSProjectId,
    CodePattern,
    NCR,
    timediff,
    totalemployee,
    timediff * totalemployee
from
    (  ...original query here... )