2016-08-01 41 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 –