navbingo
navbingo

Reputation: 223

sql query formation

Here is my SQL query:

   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    

The resulting output looks like this:

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

but want I need to frame the table like this :

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

Could you please help me out to solve this issue

thnx navin

Upvotes: 0

Views: 122

Answers (1)

Andomar
Andomar

Reputation: 238058

You could group on machinename, and use a case to sum up minutes per state:

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

Formatting the minutes is best done client side. If you have to, I guess you can in 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

Upvotes: 3

Related Questions