1

所以我想把一些不错的统计数据放在一起,但在让这个数据正常工作时遇到了问题。似乎它应该是相当基本的,但对于我的生活来说不能让它工作,我遇到的所有搜索都是人们试图将列加在一起(即简单的 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

但只会给我带来错误。如果有人至少可以为此指明正确的方向,我将不胜感激

谢谢

4

2 回答 2

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句中的事物使用表别名。

于 2013-07-13T21:35:34.133 回答
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;
于 2013-07-13T21:48:13.100 回答