簡體   English   中英

sql查詢格式

[英]sql query formation

這是我的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納文

您可以按計算機名稱分組,並用一個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM