MYSQL,使用多个SUMS,而不是将多个列汇总在一起

时间:2013-07-13 21:26:30

标签: php mysql sql count sum

所以我试图在一起得到一些不错的统计数据,但是我遇到了让这个问题起作用的问题。看起来它应该是相当基本但不能让我的生活得到这个工作和我遇到的所有搜索是人们试图将列加在一起(即一个简单的总和(a + b + c)作为t型的东西

我的表格如下:

btcfrom | btc to | btc | btctime
usera      userb   5     3204580
usera      userc   2     3450342
userb      userc   1     3428925
userc      usera   2     2358734

我想要实现的是一个返回的查询:

btcto| btcgot | timesgot | btcsent | timessent
usera    2          1        7           2
userb    5          1        1           1
userc    3          2        2           1

所以我认为可能会这样做的代码是:

SELECT btcto,SUM(btc) AS btcgot, COUNT(btc) AS timesgot 
       (SELECT btcfrom, sum(btc) as btcsent, COUNT(btc) AS timessent 
         FROM tblBots 
         GROUP BY btcfrom) AS s 
 FROM tblBots 
 WHERE btcto=s.btcfrom
 GROUP BY btcto ORDER BY btcgot DESC

但只是让我失误。如果有人能够至少指出我正确的方向,我将非常感激

感谢

2 个答案:

答案 0 :(得分:1)

根据我对结果的理解,您需要将表格聚合两次,一次在“to”上,一次在“from”上,以获得所需的摘要。

在SQL的某些方言中,您可以使用full outer join来合并这两组。您还可以使用union all然后重新汇总数据:

select BTCto, sum(TimesGot) as TimesGot, sum(BTCgot) as BTCgot,
       sum(BTCsent) as BTCsent, sum(TimeSent) as TimeSent
from ((select BTCto, count(*) as TimesGot, sum(btc) as BTCgot,
              NULL as BTCsent, NULL as TimeSent
       from tblBots t
       group by BTCto
      ) union all
      (select BTCfrom, NULL as TimesGot, NULL as BTCgot,
              count(*) as BTCsent, sum(btc) as TimeSent
       from tblBots t
       group by BTCfrom
      )
     ) t
gorup by btcTo;

由于多种原因,您的查询无效。但它试图在select子句中为子查询提供表别名。您只能对from子句中的内容使用表别名。

答案 1 :(得分:1)

您的查询只需要轻微修复:

SELECT btcto,SUM(btc) AS btcgot, COUNT(btc) AS timesgot, btcsent, timessent
from tblBots
       join (SELECT btcfrom, sum(btc) as btcsent, COUNT(*) AS timessent 
         FROM tblBots 
         GROUP BY btcfrom) AS s on btcto=s.btcfrom
GROUP BY btcto 
ORDER BY btcto 

或者,由于您实际上是在组合两个单独的查询,因此可以使用UNION:

select btcto, sum(btcgot), sum(timesgot), sum(btcsent), sum(timessent)
from (
  select btcto, sum(btc) as 'btcgot', count(*) as 'timesgot', 0 as 'btcsent', 0 as 'timessent'
  from tblBots
  group by btcto
  union
  select btcfrom, 0, 0, sum(btc), count(*)
  from tblBots
  group by btcfrom ) as q
group by btcto;