SQL查询形成

时间:2011-04-25 10:52:55

标签: sql sql-server-2005

这是我的SQL查询:

   SELECT Convert(varchar(10), hours) + ':' + Convert(varchar(10), mins) As total_time, total_minutes,machinename,description_name 
FROM   (  
        SELECT total_minutes / 60 As hours  
             , total_minutes % 60 As mins,total_minutes, machinename ,description_name 
        FROM   (  
                SELECT Sum(DateDiff(mi, 0, act_hour_as_datetime)) As total_minutes, machinename  ,description_name
                FROM   (  
                        SELECT Convert(datetime, total_time) As act_hour_as_datetime, machinename  ,description_name
                        FROM   [ven_fullreportmaster]  with(nolock)
                        INNER JOIN ven_descriptionmaster VDM ON VDM.description_id = ven_fullreportmaster.description_id
                        inner join ven_machinemaster vm on  vm.machine_id = ven_fullreportmaster.machine_id
                         where  entry_date = convert(varchar, getdate(), 105)   and  shift_type ='DAY_SHIFT' and is_task_completed ='Y'  
                       ) As derived_table  group by  machinename  ,description_name
               ) As another_derived_table  group by total_minutes, machinename ,description_name 
       ) As yet_another_derived_table  group by total_minutes, machinename,description_name,hours,mins    

结果输出如下:

total_time  total_minutes    machine_name   description_name
6:0           300              ABC            IDLE
4:0           240              DEF            RUN
1:15           75              GHI            DOWNTIME
2:00          120              ABC            DOWNTIME

但是我想要像这样构建表:

Machinename   IDLE_TIME     RUNTIME    DOWN_TIME
ABC            6:0            0          2:00
DEF              0          4:0            0
GHI              0            0          1:15

你能不能帮我解决这个问题

日Thnx 纳文

1 个答案:

答案 0 :(得分:3)

您可以对机器名进行分组,并使用case来总结每个州的分钟数:

select  machinename
,       sum(case when description_name = 'IDLE' then total_minutes 
            end) as IdleMinutes
,       sum(case when description_name = 'RUN' then total_minutes 
            end) as RunMinutes
,       sum(case when description_name = 'DOWNTIME' then total_minutes 
            end) as DownMinutes
from    YourTable
grouup by
        machinename

格式化分钟最好在客户端完成。如果必须,我想你可以在SQL中使用:

select  machinename
,       IsNull(cast(IdleMinutes / 60 as varchar(24)),'0') + ':' + 
        IsNull(cast(IdleMinutes % 60 as varchar(24)),'0') as IdleTime
,       ... repeat for busy and down ...
from    (
        ... query from above here ...
        ) as SubQueryALias