2016-08-01 51 views
2

enter image description hereMySQL查詢得到集團的SUM和最後一個記錄值BY

enter image description here

我有兩個表1是帳戶,另一種是account_spend_history灰分帳戶是父/主表和噓一張小桌子。並與賬戶OneToMany有關係(賬戶表id是ash中的一個外鍵,如account_id)。請看圖片

現在我需要獲取account.id,總花費(這是amount_spend與相同的account_id的總和)和最後花費(是在灰表中插入的最後一條記錄,並且account_id即amount_spend值與MAX(ash.id))對應的,即

id | spend_total | last_spend 
--------------------------------- 
1 | 30   | 18 
2 | 280   | 120 
3 | 20   | 20
SELECT a.id, SUM(ash.amount_spend) AS spend_total 
FROM accounts as a 
INNER JOIN account_spend_history AS ash ON ash.account_id = a.id 
GROUP BY a.id

即時得到ash.amount支出的account.id和總和,但我還需要最後的支出。如何獲得?

感謝。

回答

2

下面是一個使用correlated subquery一個選項:

SELECT a.id, SUM(ash.amount_spend) AS spend_total, 
     (SELECT amount_spend 
     FROM account_spend_history as ash2 
     WHERE ash2.account_id = a.id 
     ORDER BY ash2.id DESC LIMIT 1) as last_spend 
FROM accounts as a 
    INNER JOIN account_spend_history AS ash ON ash.account_id = a.id 
GROUP BY a.id 
+0

謝謝@sgeddes,它正在爲我,我得到了期望的輸出。 –

0

可以在子句中使用和子查詢

SELECT a.id, SUM(ash.amount_spend) AS spend_total, x.last_spend 
FROM accounts as a 
INNER JOIN account_spend_history AS ash ON ash.account_id = a.id 
INNER JOIN ( 
    select account_id, last_spend, start_date 
    from account_spend_history 
    where (start_date, acoount_id) in ( 
     select max(start_date), account_id 
     from account_spend_history 
     group by account_id 
    ) 
) x on x.id = a.id 
GROUP BY a.id 
1

你可以得到MAX(ash.id)以及在您的查詢,然後用它來連接回到account_spend_history表格:

SELECT id, spend_total, amount_send as last_spend 
FROM (
    SELECT a.id, SUM(ash.amount_spend) AS spend_total, MAX(ash.id) AS ash_id 
    FROM accounts as a 
    INNER JOIN account_spend_history AS ash ON ash.account_id = a.id 
    GROUP BY a.id) AS t1 
INNER JOIN account_spend_history AS ash ON ash.id = t1.ash_id 
+0

我喜歡這種方法比我發佈的更好... – sgeddes

+0

嗨@Giorgos Betsos,謝謝你的幫助。我寫了查詢,但我得到了一個錯誤。 **#1054 - 在 '字段列表' 未知列 'amount_send' ** SELECT t1.id, spend_total, amount_send AS last_spend FROM (SELECT a.id, SUM(ash.amount_spend) AS spend_total, MAX(ash.id)AS ash_id FROM的賬戶作爲 INNER JOIN account_spend_history AS灰ON ash.account_id = a.id GROUP BY a.id )爲T1 INNER JOIN account_spend_history AS灰ON灰。 id = t1.ash_id –