0

整天都在为此苦苦挣扎,现在尝试各种组合而没有任何快乐,如果有人可以提供帮助吗?我使用 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

任何帮助表示赞赏。

G

4

2 回答 2

1

你可以尝试这样的事情:

SELECT *, If(ContactFullName is null, 1, 0) as rolledup 
FROM ( .... giant inner select goes here ...)
ORDER BY rolledup asc, q.profit desc
于 2012-09-13T14:16:52.103 回答
0

当您按利润降序订购时,您会将汇总列作为第一行,这没有意义。所以我想您不能那样做。据我所知,您不能简单地更改一列的顺序并保持其余列的顺序不变。

于 2012-09-13T14:10:10.403 回答