2015-12-03 30 views
0

兩個不同的where語句即時創建一個sql結果,顯示客戶的backupjobs成功率(%)。創建一個計算列從同一個表中使用組的

不知何故,我想下面的查詢相結合,實現這一目標:

select [colCustomerID],count(*) as Totalbackups FROM [BackupStat].[dbo].[tblJobSummary] group by [colCustomerID] 

select [colCustomerID],count(*) as Failedbackups FROM [BackupStat].[dbo].[tblJobSummary] where [colStatus] !='Success' and [colStatus] !='Warning' group by [colCustomerID] 

結果的第一個查詢是這個樣子:

colCustomerID Totalbackups 
EXK-1670001 315 
INK-2325001 8 
INK-995001 5 
INK-2326001 10 
INK-1729001 7 
INK-237001 2 
GBG-3795001 4 
INK-3422001 4 
INK-3768001 138 
INK-3780001 10 
+0

你爲什麼不加入表格並進行計算? – Walucas

回答

0

您可以創建2個個子查詢,然後執行計算。您可能想要更改十進制轉換中的精度和縮放比例。

編輯:添加了Totalbackups列。

select 
    tb.colCustomerID, 
    tb.Totalbackups, 
    convert(decimal(5,2), fb.Failedbackups)/convert(decimal(5,2), tb.Totalbackups) 
from  
(
    select 
     [colCustomerID], 
     count(*) as Totalbackups 
    FROM [BackupStat].[dbo].[tblJobSummary] 
    group by [colCustomerID] 
) tb 
    inner join 
     (
      select 
       [colCustomerID], 
       count(*) as Failedbackups 
      FROM [BackupStat].[dbo].[tblJobSummary] 
      where [colStatus] !='Success' 
       and [colStatus] !='Warning' 
      group by [colCustomerID] 
     ) fb 
      on tb.colCustomerID = fb.colCustomerID 

希望這有助於!