mySQL单表总结

时间:2014-05-09 06:51:24

标签: mysql

我有一张桌子"转移"列(_from,_to,amount)。对于给定的用户,我需要列出所有其他用户,他们与该用户一起转移的总金额以及他们转移的总金额。

例如,如果"转移"是:

| _from | _to | amount |
------------------------
|   A   |  B  |  100   |
|   B   |  A  |  100   |
|   A   |  C  |  300   |
|   B   |  D  |  500   |

用户" A"的查询结果集将是:

| user  | myTransfers | totalTransfers | <--- same for whoever you query
----------------------------------------
|   A   |     500     |      500       |
|   B   |     200     |      700       |
|   C   |     300     |      300       |
|   D   |     0       |      500       |

起初这似乎微不足道,但我似乎无法开始工作。我在这个问题上抛出子查询是错误的吗?还是有更优雅的解决方案?

1 个答案:

答案 0 :(得分:1)

终于明白了,但你可能会发现更容易的东西。

子查询执行&#34;展平&#34;将所有可能的用户(来自或来自)作为用户。

select 
  user, 
 --here you choose the user you wanna query
 sum(case when correspondant = 'A' or user = 'A' then amount else 0 end),
 sum(amount)
from
 (select 
    _to as correspondant,
    amount, 
    _from as user
  from Table1
  union all
  select
    _from as correspondant,
    amount, 
    _to as user
  from Table1) s
group by user

请参阅SqlFiddle