2015-04-17 73 views
0

我试图建立MySQL查询与多个连接蒙山加盟值的总和。有3个表格:custmer,帐户和存款。帐户和存款将通过其customer_id字段加入到客户中。在查询结束时,所有的客户都被他们GROUP_ID分组:MySQL查询:和列值具有鲜明的另一列

SELECT customer.*, 
COUNT(DISTINCT account.id) as account_count, 
SUM(deposit.amount)/(COUNT(deposit.id)/COUNT(DISTINCT deposit.id)) as deposit_sum, 
SUM(???) as deposit_first_sum 
FROM customer 
    LEFT JOIN account ON account.customer_id = customer.id 
    LEFT JOIN deposit ON deposit.customer_id = customer.id 
GROUP BY customer.group_id 

的问题是:加入了行被复制,而我不得不做出一些分析:SUMM所有存款金额 - 你可以在这里看到我的解决办法为deposit_sum。但真正的问题是总结“客户的首次存款”。分组结果之前,我们可能会看到有这样的:

... deposit.id deposit.customer_id deposit.amount 
...  1    1    10 
...  2    1    20 
...  3    2    15 
...  4    2    30 

所以我需要的是总结仅第一量为每CUSTOMER_ID(10 + 15),这将是“deposit_first_sum”。这里

一个限制是我很害怕,因为它需要大量的内存,同时从存款表让所有存款行,我不能用“左连接(SELECT ... FROM存款)作为定金”。

我在这里看到了一个有趣的答案Sum values from one column if Index column is distinct? 但它适用于MSSQL。

所以,问题是:有没有办法来概括所有的第一存款,而无需使用JOIN(SELECT)或可能存在与JOIN(SELECT)的方式,但有些记忆经济把戏?

UPDATE。 我们也可能使用与帐户表相关的deposit.account_id。

+0

可以发布当前查询的结果集? – Avidos

+0

...存款记录customer_id而不是account_id? –

+0

并且用户会拥有多个帐户? –

回答

0

此查询将为您提供customer_idamount首次存款,而无需使用子查询。

select d1.customer_id, d1.amount 
    from deposit d1 
    left join deposit d2 
     on d1.customer_id = d2.customer_id and d1.id > d2.id 
    where d2.id is null; 

很明显,你可以得到sum还有:

select sum(d1.amount) total_first_deposit 
    from deposit d1 
    left join deposit d2 
     on d1.customer_id = d2.customer_id and d1.id > d2.id 
    where d2.id is null; 

您还可以得到总和,以及第一存款这样的总和:

select sum(d3.amount) total_deposit, sum(case when d3.id = d1.id then d3.amount end) total_first_deposit 
    from deposit d1 
    left join deposit d2 
     on d1.customer_id = d2.customer_id and d1.id > d2.id 
    inner join deposit d3 
     on d1.customer_id = d3.customer_id and d2.id is null 
+0

我需要更多地了解表格之间的关系,然后才能在答案中包含“帐户”表。具体来说,如果用户可以有多个帐户。如果可以的话,真正的存款应该记录在账户上,而不是客户,否则这会变成..痛苦的 –

+0

谢谢!通过account_id加入是这个问题的关键。 –

+0

啊真棒。是的,从存款,客户到账户总是很难。 –