对聚合函数求和

Summing a aggregate function

我试图通过使用嵌套的 select 语句对聚合函数中的总和进行求和,然后我在最后有一个分组依据,但我收到一个错误,关键字是预计不会。

代码如下:

SELECT SUM(TOTAL) as CURTOTAL, SUM(LYTOTAL) as CURLYTOTAL
from
(select 
pf.*, ps.*, st.*, RANK() OVER (ORDER BY JULsaless desc) as TOTRANK,
 JANSALESS + FEBSALESS + MARSALESS + APRSALESS + MAYSALESS + JUNSALESS + JULSALES as TOTAL,
JANLYSAL + FEBLYSAL + MARLYSAL + APRLYSAL + MAYLYSAL + JUNLYSAL + JULLYSAL as LYTOTAL` 
from 
payssfile pf left joinpayssspec ps on pf.str#` = ps.str# and pf.item# = ps.item#  join storefile 
st on
pf.str# = st.str# where(year = 2015 and totaltype = '' and pf.str# =38))` group by pf.str#;`

然后当我去 运行 时收到这条消息:

The keyword BY was not expected here. A syntax error was detected at keyword BY. The partial list of valid tokens is FOR USE SKIP WAIT WITH FETCH ORDER UNION EXCEPT OPTIMIZE.

无论您的 DBMS 是什么,您都缺少一个别名。 您应该 始终 为您正在使用的派生 table 指定一个别名。

派生示例 table

select...
from (
-- this part of the query is a derived table:
select ... from ...
) as <ALIAS_HERE> -- must give derived table an alias

这就是您在 GROUP BY

附近出现错误的原因

在您的特定示例中,只需替换

)) group by pf.str#;

)) foo group by pf.str#; 
-- here you will name your derived table foo, to be able to call it's columns by foo.column_name

这是关于 SO 的类似问题的reference

您似乎没有为子查询指定别名,pf 是子查询中 table 的名称,但不是子查询本身。因此,按功能分组被破坏。