小编典典

SQL:如何在按部分分组的查询中使用子查询?

sql

如何在按部分分组的查询中使用子查询?

我使用SQL Server 2008 R2和Delphi 2010

我收到此错误:

Cannot perform an aggregate function on an expression 
containing an aggregate or a sub query.

像这个查询:

select 
    t1.sen, 
    sum(t1.d1)as d1, 
    sum(t1.d2)as d2, 
    sum(t1.d1+t1.d2) as d_sum,
    Round((sum((1000*(t1.d1+t1.d2))/(9500-(
       select sum(t2.t_shab+t2.t_rooz) 
       from tbl1 t2 
       where FCode=81 AND DCode=1 AND t2.sen<=t1.sen
    )))),1) as SSS 
from 
    tbl1 t1 
where 
    FCode = 81 
    AND DCode = 1

按t1.sen分组


阅读 268

收藏
2021-04-14

共1个答案

小编典典

这是真实的方式

create function getSumBSen2(@pfcode INT, @pdcode INT, @pSen INT) returns int
as
begin
     declare @r int; 
     select 
        @r= sum(t2.t_shab + t2.t_rooz)
     from 
         tbl1 t2 
     where 
         t2.FCode = @pfcode 
     and t2.DCode = @pdcode 
     and t2.sen <= @pSen;

     return (@r);
end;
GO

select 
    t1.sen, 
    sum(t1.d1) as d1, 
    sum(t1.d2) as d2, 
    sum(t1.d1 + t1.d2) as d_sum,
    Round((sum((1000*(t1.d1+t1.d2)+0.01)/(9500-(dbo.getSumBSen2(t1.FCode, t1.DCode, t1.sen))))),1) as SSS 
from 
    tbl1 t1
where 
    t1.FCode = 81 
and t1.DCode = 1 
group by 
    t1.sen;
2021-04-14