SQL : How can I use sub query in a query with group by section?

前端 未结 4 1220
一个人的身影
一个人的身影 2021-01-28 23:03

How can I use sub query in a query with group by section?

I use SQL Server 2008 R2 AND Delphi 2010

I receive this error:

Cannot perform an aggreg         


        
4条回答
  •  清歌不尽
    2021-01-28 23:44

    Try this:

    DECLARE @tbl1 AS TABLE
        (
         FCode INT
        ,DCode INT
        ,sen INT
        ,d1 INT
        ,d2 INT
        ,t_shab INT
        ,t_rooz INT
        ) ;
    
    SELECT  *
    FROM    (
             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 - factor.factor))),
                          1) AS SSS
             FROM   @tbl1 AS t1
             INNER JOIN (
                         SELECT t1.sen
                               ,SUM(t2.t_shab + t2.t_rooz) AS factor
                         FROM   @tbl1 AS t2
                         INNER JOIN @tbl1 AS t1
                                ON t1.FCode = 81
                                   AND t1.DCode = 1
                                   AND t2.FCode = 81
                                   AND t2.DCode = 1
                                   AND t2.sen <= t1.sen
                         GROUP BY t1.sen
                        ) AS factor
                    ON factor.sen = t1.sen
             WHERE  FCode = 81
                    AND DCode = 1
             GROUP BY t1.sen
            ) AS X ;
    

提交回复
热议问题