如何获得不同代码的总时间%

时间:2011-04-27 19:15:38

标签: sql sql-server tsql sql-server-2008

我有一个名为Timetable的表,数据如下:

Hours   Code    FiMonth  Mgr
16      OT      2011M1   Sam
0.25    DT      2011M1   Peter
1.75    HNE     2011M1   george
6.5     DT      2010M1   Peter
3.25    OT      2010M1   Sam
0.5     DT      2010M2   Sam
30      HNE     2011M1   John

现在我必须计算时间%和得到该值的公式:

  

时间%=总和(DT + OT)小时/(DT + OT + HNE)小时

我将查询写成:

SELECT  ( ( SELECT  SUM(CONVERT(FLOAT, [Hours])) AS [Hours]
            FROM    Timetable d
            WHERE   d.code IN ( 'OT','DT') 
          )
          / ( SELECT    SUM(CONVERT(FLOAT, [Hours])) AS [Hours]
              FROM      Timetable t
              WHERE     t.code IN ( 'OT', 'DT','HNE')
           ) ) AS Time%
           FROM    Timetable
           GROUP BY Mgr

我必须在我的存储过程中使用此值,并且我有许多这样的列。所以,我不想为一列编写这么多代码。

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

WITH Timetable([Hours],code,FiMonth,Mgr) as
(
SELECT 16,'OT','2011M1','Sam' UNION ALL
SELECT 0.25,'DT','2011M1','Peter' UNION ALL
SELECT 1.75,'HNE','2011M1','george' UNION ALL
SELECT 6.5,'DT','2010M1','Peter' UNION ALL
SELECT 3.25,'OT','2010M1','Sam' UNION ALL
SELECT 0.5,'DT','2010M2','Sam' UNION ALL
SELECT 30,'HNE','2011M1','John'
)
SELECT Mgr,
       SUM(CASE
             WHEN code IN ( 'OT', 'DT' ) THEN CAST([Hours] AS FLOAT)
             ELSE 0
           END)/ NULLIF(SUM(CAST([Hours] AS FLOAT)),0) AS [Time%]
FROM   Timetable t
WHERE  code IN ( 'OT', 'DT', 'HNE' )
GROUP  BY Mgr