使用多个聚合函数 - 求和和计数

时间:2015-11-20 20:53:35

标签: sql-server

我在网站上尝试了几个解决方案,但找不到一个有效的解决方案。请帮忙! 除了对report_names采取一些自由之外,数据对于我想要完成的事情是现实的,并且只是我所反对的一小部分,大约97K行的数据具有相同类型的分支重复,file_count,report_name ...文件编号是唯一的,并且无关紧要。它是出于我的问题的信息目的,并解释了为什么金额是唯一的 - 它们与file_name绑定 我正在寻找一个带有两个金额之和的report_name。

以下是我的查询的当前结果:

branch    file_count file_volume   net_profit  report_name    file_number
Northeast 1          $200,000.00  $200,000.00  bogart.hump.new      12345
Northeast 1          $195,000.00  $197,837.00  bogart.hump.new      23456
Northeast 1          $111,500.00  $113,172.00  bogart.hump.new      34567
Northwest 1           $66,000.00   -$1,500.18  jolie.angela.new     45678
Northwest 1          $159,856.00   -$2,745.58  jolie.angela.new     56789
Northwest 1          $140,998.00   -$2,421.69  jolie.angela.new     67890
Southwest 1           $74,000.00   $73,904.00  Man.bat.net          78901
Southwest 1          $186,245.00   -$4,231.25  Man.bat.net          89012
Southwest 1           $72,375.00   $73,641.00  Man.bat.net          90123
Southeast 1           $79,575.00    -$1,821.76 zep.led.new          1234A
Southeast 1          $268,600.00   $268,600.00 zep.led.new          2345A
Southeast 1           $77,103.00    -$1,751.68 zep.led.new          3456A

这就是我要找的:

branch    file_count file_volume    net_profit  report_name     file_number
Northeast 3          $506,500.00   $511,009.00  bogart.hump.new 
Northwest 3          $366,854.00    -$6,667.45  jolie.angela.new 
Southwest 3          $332,620.00   $143,313.75  Man.bat.net 
Southeast 3          $425,278.00   $265,026.56  zep.led.new 

我的查询:

SELECT 
branch,
count(filenumber) AS file_count,
sum(fileAmount) AS file_amount, 
sum(netprofit*-1) AS net_profit,
concat(d2.lastname,'.',d2.firstname,'.','new') AS report_name,

FROM user.summary u
inner join user.db1 d1 ON d1.loaname = u.loaname 
inner join user.db2 d2 ON d2.cn = u.loaname

WHERE d2.filedate = '2015-09-01'
AND filenumber is not null

GROUP BY branch,concat(d2.lastname,'.',d2.firstname,'.','new')

1 个答案:

答案 0 :(得分:0)

我在您当前查询中看到的唯一问题是,您在此行的末尾有一个逗号,会出现语法错误:

concat(d2.lastname,'.',d2.firstname,'.','new') AS report_name,

如果您想要所需结果集中显示的空白字段file_number,则可以保留逗号并通过添加空白字段跟随它:

concat(d2.lastname,'.',d2.firstname,'.','new') AS report_name,
'' file_number