将ORDER BY与ROLLUP一起使用

时间:2012-09-13 13:56:32

标签: mysql

如果有人能提供帮助的话,现在一整天都在努力尝试各种组合而没有任何喜悦?我使用WITH ROLLUP来总计一个Total列,它将一行添加到输出每列总和的表的脚。

我现在需要订购最后一列[利润]下降,因此最高数字位于顶部。我使用下面的查询实现了这一点,但它也对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

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

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

答案 1 :(得分:0)

当您按利润desc订购时,您将获得第一行的汇总列,这是没有意义的。所以我猜你不能这样做。据我所知,你不能简单地改变一个coulmn的顺序,并保持其余的列顺序固定。