2012-09-06 66 views
0

早上好,mysql查詢顯示有日期字段的案例已完成&總行數量,我想根據總案例進行計算,但不確定是否可以在一個查詢中執行所有操作。例如,當前查詢輸出子查詢由繞過where子句

Aug Sep Nov Total 
10 20 20 50 

我需要它什麼輸出是下面的,所以我說上面的TotDB網上看到,如果這將有助於爲正在

 SELECT * from(
    Select Count(b.CaseID) As TotDB 
    from tblcontacts a 
    Inner Join tblcases b 
    On a.ContactID = b.ContactAssignedTo)a 
CROSS JOIN 
    (Select 
    Sum(Month(b.StatusSubmittedDate) = 8) As Aug, 
    Sum(Month(b.StatusSubmittedDate) = 9) As Sep, 
    Sum(Month(b.StatusSubmittedDate) = 10) As Oct, 
    Count(b.CaseID) As Total, 
    ROUND (100*Count(b.CaseID)/Count(b.CaseID),2) As Conversion 
From 
    tblcontacts a Inner Join 
    tblcases b On a.ContactID = b.ContactAssignedTo 
Where 
    b.StatusSubmittedDate > '2012 - 01 - 01' 
Group By 
    a.ContactFullName With Rollup 
Having 
    Sum(b.CaseCommission) > 0.01)b 

的代碼,它沒「T。我需要找出是我可以在此查詢繞過其中一列/ having子句顯示所有記錄

Aug Sep Nov Tot TotDB %Converted 
10 20 20 50 100 50% 

感謝

+0

你究竟在做什麼?你會解釋更多嗎? –

+0

當前查詢在2012-01-01> 0.01以後使用where和必須將數據過濾爲僅有數據的記錄。我需要TotDB列繞過此並顯示數據庫中的所有記錄的計數? – gary

+0

'b.StatusSubmittedDate> 2012 - 01 - 01'甚至可以工作嗎?你不是在'b.StatusSubmittedDate> 2010'嗎?嘗試'b.StatusSubmittedDate>'2012-01-01''? – Konerak

回答

1

也許你應該這樣做:

select Aug,Sep, Nov, Tot,TotDB,(Tot/TotDB*1.0)*100 as '%Converted' 
from 
(SELECT * from(
    Select Count(b.CaseDate) As TotDB 
    from tblcontacts a 
    Inner Join tblcases b 
    On a.ContactID = b.ContactAssignedTo)a 
CROSS JOIN 
    (select 
     Sum(Month(b.StatusSubmittedDate) = 9) As Sep, 
     Sum(Month(b.StatusSubmittedDate) = 10) As Oct, 
     Sum(Month(b.StatusSubmittedDate) = 11) As Nov, 
     Count(b.CaseID) As Total, 
    From tblcontacts a 
    Inner Join tblcases b 
    On a.ContactID = b.ContactAssignedTo 
    Where 
     b.StatusSubmittedDate > '2012-01-01' 
    Group By 
     a.ContactFullName With Rollup 
    Having 
     Sum(b.CaseCommission) > 0.01)b)c 
+0

@Konerak,謝謝是的,它的確如此工作,但我現在添加了'2012-01-01'。 – gary

+0

非常感謝您的建議,確實在該表中添加了具有全部記錄的另一列,然後我試圖使用該列來計算總數之間的%,但它只是返回相同的值,我更新了上面顯示的原始代碼。 calc是引用相同的字段,我需要它從1和第二個查詢計算字段?這是有道理的.. – gary

+0

@gary:我已經更新了我的答案.. plz檢查 –

0

你不能在一個簡單的查詢中做到這一點。

要做到這一點的正確方法是執行第二個查詢,而不使用where子句。真。

如果你必須這樣做,在一個查詢中,至少使用一個聯盟:

/* old query */ 
SELECT a,b,c from t1,t2,t3 where d=e group by a having b>f 
UNION 
select 'total',COUNT(*),NULL /*need the same amount of rows*/ 
from t1,t2,t3 

和你的客戶方對待排在那裏a='total'不同。但這是一個黑客。我會建議你使用兩個查詢。