需要sql查询

时间:2012-02-20 07:59:09

标签: sql sql-server-2005

这是我的查询,

select a.nvrEquipment as [Equiment Name],a.Availability,b.Breakdown,c.Idle from 
(select nvrEquipment,sum(fltQuantity) as [Availability] from tblEquipment 
where intstatus in(1,2,3) group by nvrEquipment) a left join 
(select nvrEquipment,sum(fltQuantity) as [Breakdown] from tblEquipment 
where intstatus = 2 group by nvrEquipment) b on a.nvrEquipment=b.nvrEquipment left join
(select nvrEquipment,sum(fltQuantity) as [Idle] from tblEquipment 
where intstatus = 3 group by nvrEquipment) c on a.nvrEquipment=c.nvrEquipment

我需要在%:

中使用另一列“利用率”

公式是:

Utilization in % = (Breakdown + Idle) / Avalilability * 100

Equiment Name  Availability      Breakdown    Idle    Utilization
Crane            3             1            1

1 个答案:

答案 0 :(得分:1)

看起来很简单:

select a.nvrEquipment as [Equiment Name],a.Availability,b.Breakdown,c.Idle,
(b.Breakdown + c.Idle) * 100 / NULLIF(a.Availability, 0) as Utilization
from 
(select nvrEquipment,sum(fltQuantity) as [Availability] from tblEquipment 
where intstatus in(1,2,3) group by nvrEquipment) a left join 
(select nvrEquipment,sum(fltQuantity) as [Breakdown] from tblEquipment 
where intstatus = 2 group by nvrEquipment) b on a.nvrEquipment=b.nvrEquipment left join
(select nvrEquipment,sum(fltQuantity) as [Idle] from tblEquipment 
where intstatus = 3 group by nvrEquipment) c on a.nvrEquipment=c.nvrEquipment
  • 我在划分之前相乘以避免INTEGER舍入,如果有的话。
  • 我使用NULLIF来处理除零。