2011-04-25 55 views
0

这里是我的SQL查询: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 纳文

回答

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 
+0

thnx alot ..it工作正常 – navbingo 2011-04-25 15:05:17