2011-04-25 56 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