如何提取我的查询以找到平均值

时间:2016-07-07 11:12:43

标签: sql sql-server

我有这样的表

  name  M1    m2   Tot
  a      20   30    50
  b      10   20    30    
  a      20   10    30
  a      30   15    45

使用查询

SELECT name,
    ISNULL([1],0) AS tot1,
    ISNULL([2],0) AS tot2,
    ISNULL([3],0) AS tot3
 FROM (SELECT ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) RN,
              name, Total
       FROM  T
      ) S
 PIVOT (MAX(Total) FOR RN IN ([1],[2],[3])) AS PVT

我得出像

name   Tot1  Tot2  Tot3
 a      50     30    45
 b      30     0      0

现在我需要再添加一列来查找平均值。所以我需要像

这样的输出
name   Tot1  Tot2  Tot3  **Avg**
 a      50     30    45    **42**
 b      30     0      0    **10**

如何解析我的查询..

2 个答案:

答案 0 :(得分:2)

试试这个

SELECT name,
    ISNULL([1],0) AS tot1,
    ISNULL([2],0) AS tot2,
    ISNULL([3],0) AS tot3,
    (ISNULL([1],0) + ISNULL([2],0) + ISNULL([3],0) )/3 AS [AVG]
 FROM (SELECT ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) RN,
              name, tot
       FROM  Example
      ) S
 PIVOT (MAX(tot) FOR RN IN ([1],[2],[3])) AS PVT

答案 1 :(得分:1)

使用子查询:

with q as (<your query here>)
select q.*, (tot1 + tot2 + tot3) / 3
from q;