2014-01-30 66 views
0

我想将两列值乘以第三列。这里是我的查询:SQL查询将两列值乘以第三列

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

'SELECT ... ..,timediff * totalemployee as newcolumn FROM' – Mihai

+0

如果那么简单,我就不会在这里发布查询。 – Mahajan344

+0

我不确定你可以在select中重用别名,如果不使用整个表达式的话。 – Mihai

回答

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) 

另外,在换另一个查询整个现有的查询,并乘以calcualted列:

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