汇总多个ORDER BY列

时间:2012-10-03 11:58:12

标签: mysql

我创建了this问题,现在已经处理了女巫问题,但我对同一个问题还有另一个困难:

SELECT
  t.type,
  SUM( t.external_account )
FROM
  u_contracts c,
  u_data u,
  u_transactions t
WHERE
  c.user_id = u.id
  AND t.contract_id = c.id
  AND t.nulled =0
  AND DATE (c.init_date) < DATE (u.dead)
  AND u.dead IS NOT NULL
  AND t.type != 'repay'
GROUP BY
  t.type
ORDER BY
  FIELD( t.type, 'initial', 'comission', 'overpay', 'penalty', 'penalty2' );

我得到的结果如下:

+-----------+---------------------------+
| type      | SUM( t.external_account ) |
+-----------+---------------------------+
| prolong   |                 360560.00 |
| reg       |                   3889.00 |
| reg2      |                    301.20 |
| initial   |                 610628.54 |
| comission |                 125623.49 |
| overpay   |                   6461.57 |
| penalty   |                  21461.52 |
| penalty2  |                   4010.00 |
+-----------+---------------------------+

我需要整理类型延长 + reg + reg2 的结果,并将它们添加到列表的末尾。

现在我完全不知道如何根据GROUP BY t.type请求得出它们的总和。

1 个答案:

答案 0 :(得分:3)

尝试一下:

SELECT 
    t.type,
    SUM(t.external_account)
FROM
(
    SELECT
      CASE t.type
        WHEN 'prolong' THEN 'prolong + reg + reg2'
        WHEN 'reg' THEN 'prolong + reg + reg2'
        WHEN 'reg2' THEN 'prolong + reg + reg2'
        ELSE t.type
      END AS type,
      t.external_account
    FROM
      u_contracts c,
      u_data u,
      u_transactions t
    WHERE
      c.user_id = u.id
      AND t.contract_id = c.id
      AND t.nulled =0
      AND DATE (c.init_date) < DATE (u.dead)
      AND u.dead IS NOT NULL
      AND t.type != 'repay'
) t 
GROUP BY
      t.type
ORDER BY
  FIELD( t.type, 'initial', 'comission', 'overpay', 'penalty', 'penalty2' );