2012-10-03 96 views
1

我創建this問題,女巫現在的照顧,但我有相同的查詢另一種鬥爭:總結多個ORDER BY列

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的請求。

+0

取而代之的是3個系你提的,還是除了他們? –

+0

而不是他們 – Peon

回答

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'); 
+0

謝謝你,作品像一個魅力:) – Peon

+0

很高興它幫助:) – Vikdor

+3

+1我會把CASE放在GROUP BY中,但解決方案几乎相同,你打敗我:) –