SQL结合了AVG和RANK

时间:2014-12-17 11:31:28

标签: tsql sql-server-2008-r2

我有一个查询

VariableWastage
          AS ( SELECT   ID ,
                        SCRAPVAR ,
                        COUNT(RECCODE) AS [COUNT] ,
                        RANK() OVER ( PARTITION BY ID ORDER BY COUNT(RECCODE) DESC ) AS [RANK]
               FROM     RECIPE
               WHERE    ITEMTYPE != 2
                        AND CAST(CAST(SCRAPVAR AS FLOAT) AS INT) != 0 -- excluding SCRAPVAR 0
GROUP BY                ID ,
                        SCRAPVAR
             )SELECT * FROM VariableWastage

给出了结果

enter image description here

如果突出显示行,如何为每个项目生成一行并在重复项之间获取AVG SCRAPVAR值?所以基本上在结果​​集中我希望看到

ABR001    1.025
ABR002    1.025
ABR003    1.025

我只想AVG RANK输出基本上......谢谢!

1 个答案:

答案 0 :(得分:0)

找到答案......只需按照...中的AVERAGE进行...

VariableWastage
               AS ( SELECT   ID ,
                             SCRAPVAR ,
                             COUNT(RECCODE) AS [COUNT] ,
                             RANK() OVER ( PARTITION BY ID ORDER BY COUNT(RECCODE) DESC ) AS [RANK]
                    FROM     RECIPE
                    WHERE    ITEMTYPE != 2
                             AND CAST(CAST(SCRAPVAR AS FLOAT) AS INT) != 0 -- excluding SCRAPVAR 0
     GROUP BY                ID ,
                             SCRAPVAR
                  )SELECT ID, AVG(CAST(SCRAPVAR AS DECIMAL(4, 2))) as SCRAPVAR, COUNT, RANK   FROM VariableWastage GROUP BY ID, COUNT, RANK