2011-12-29 73 views
1

在這裏,我以小時和分鐘獲得了「ProcessTime」,但在幾秒鐘情況下,只有我檢查了相反的情況(見下面的代碼)如何提高這個sql查詢

有什麼辦法改善嗎?

select convert(varchar(10),ScanDate,101) as [Date], tmb.WO, tc.WOCategory, count(IdSingle) QtyProd, tb.Brand, tm.Model, 
     (case when (DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8)))/60%24 > 0) then 
      convert(varchar(5), DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8)))/60%24) + 'h '    
       else 
      '' 
     end) + 
     (case when (DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8)))%60 > 0) then 
      convert(varchar(5), DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8)))%60) + 'm'    
       else 
      '' 
     end) +   
     (case when 
      (DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8)))/60%24 <= 0) and 
      (DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8)))%60 <= 0) then 
      '< 1 min' 
      else 
      '' 
     end) ProcessTime 
+0

你使用的是什麼版本的sql? – Hogan 2011-12-30 22:17:30

+0

後悔,sql server 2005 – Somebody 2012-01-03 19:50:38

回答

1

使用SQL Server 2005,您可以使用CTE來改進此查詢。
類似這樣的:

;WITH minmax AS 
(
    SELECT someKey, 
      DateDiff(mi, Min(convert(varchar(10),ScanDate,8)), Max(convert(varchar(10),ScanDate,8))) as mdiff 
    FROM tablename 
    GROUP BY fieldName 
) 
Select convert(varchar(10),ScanDate,101) as [Date], tmb.WO, tc.WOCategory, count(IdSingle) QtyProd, tb.Brand, tm.Model, 
     (case when (mdiff/60%24 > 0) then 
      convert(varchar(5), mdiff/60%24) + 'h '    
       else 
      '' 
     end) + 
     (case when (mdiff%60 > 0) then 
      convert(varchar(5), mdiff%60) + 'm'    
       else 
      '' 
     end) +   
     (case when 
      (DateDiff(mi, mdiff/60%24 <= 0) and (DateDiff(mi, mdiff%60 <= 0) then 
      '< 1 min' 
      else 
      '' 
     end) ProcessTime 
from tablename 
join minmax on tablename.somekey = minmax.somekey 
+0

humm ...有意思,謝謝。 – Somebody 2012-01-03 20:40:35

+0

我認爲還有另一種改善的方法,但我必須去開會。 – Hogan 2012-01-03 21:00:35