2012-09-13 80 views
0

一整天都在努力嘗試各種組合,如果有人可以幫忙,就沒有任何快樂吧?我使用WITH ROLLUP來總計一個Total列,它向輸出每列總和的表格的腳增加一行。使用ORDER BY和ROLLUP

我現在需要訂購最後一列[利潤]降序,所以最高的數字在頂部。我已經實現了這個使用下面的查詢,但它也排序ROLLUP行,是否有一個方法將彙總作爲一個單獨的實體,所以ORDER BY只在正常記錄上完成?

Select 
    * 
From 
    (Select 
     c.ContactFullName As Adviser, 
     Sum(If(Month(b.CaseDate) = 1, b.LeadCost, 0)) As Jan, 
     Sum(If(Month(b.CaseDate) = 2, b.LeadCost, 0)) As Feb, 
     Sum(If(Month(b.CaseDate) = 3, b.LeadCost, 0)) As Mar, 
     Sum(If(Month(b.CaseDate) = 4, b.LeadCost, 0)) As Apr, 
     Sum(If(Month(b.CaseDate) = 5, b.LeadCost, 0)) As May, 
     Sum(If(Month(b.CaseDate) = 6, b.LeadCost, 0)) As Jun, 
     Sum(If(Month(b.CaseDate) = 7, b.LeadCost, 0)) As Jul, 
     Sum(If(Month(b.CaseDate) = 8, b.LeadCost, 0)) As Aug, 
     Sum(If(Month(b.CaseDate) = 9, b.LeadCost, 0)) As Sep, 
     Sum(If(Month(b.CaseDate) = 10, b.LeadCost, 0)) As Oct, 
     Sum(If(Month(b.CaseDate) = 11, b.LeadCost, 0)) As Nov, 
     Sum(If(Month(b.CaseDate) = 12, b.LeadCost, 0)) As Decb, 
     Sum(b.LeadCost) As LeadCosts, 
     Sum(b.CaseCommission) As GrossComm, 
     (Sum(b.CaseCommission) * 40/100) As GHL_Comm, 
     (Sum(b.CaseCommission) * 40/100 - Sum(b.LeadCost)) As Profit 
    From 
     tblcontacts a Inner Join 
     tblcases b On a.ContactID = b.ContactID Inner Join 
     mi_tblcontacts c On c.Mi_ContactID = b.ContactAssignedTo Inner Join 
     tblreferral d On d.RefferalID = a.ContactReferrelSource 
    Group By 
     c.ContactFullName With Rollup) q 
Order By 
    q.Profit Desc 

任何幫助表示讚賞。

回答

1

你可以嘗試這樣的事:

SELECT *, If(ContactFullName is null, 1, 0) as rolledup 
FROM (.... giant inner select goes here ...) 
ORDER BY rolledup asc, q.profit desc 
+0

謝謝您的回答,你好當我嘗試這一點,告訴我「在字段列表中未知列ContactFullName」? 乾杯 – gary

+1

嗨,我只是將ContactFullName更改爲q.adviser,它工作得很好。謝謝你的幫助。 – gary

0

當您通過利潤倒序那麼你將得到彙總列第一行,這是不是meaningfull.So我猜你不能做這樣的。據我所知,你不能簡單地改變一個coulmn的順序,並保持其餘的列順序固定。