SQL Count然后是特定学生的Sum和average

时间:2018-03-06 15:20:49

标签: sql sql-server

我有一张学生表,他们的分数由Submitdate列出。我正在尝试计算每个学生的SUM,TOTAL和AVERAGE。这是我的数据表:

StudentsTbl
-------------
ID G1 G2  Submitdate
-------------------
01 8  9   2017-11-06
01 9  10  2017-11-18
01 7  8   2017-12-09
02 6  8   2017-10-08
02 9  10  2017-11-25
03 9  10  2017-10-18
03 7  6   2017-11-15
03 8  9   2017-12-08
03 7  8   2017-12-25

我创建了这个查询来计算每个学生的平均值和总数,但它不起作用:

SELECT AVG(G1) AS G1
     , AVG(G2) AS G2
     , (AVG(G1) + AVG(G2)) AS Total
     , (AVG(G1) + AVG(G2))/2 AS Average
FROM StudentsTbl
GROUP BY G1, G2

以下是我想要的输出:

ID  G1    G2   Total Average
--------------------------
01 8.00  9.00  17.00  8.50
02 7.50  9.00  16.50  9.75
03 7.75  8.25  16.00  8.00

2 个答案:

答案 0 :(得分:3)

您需要按ID分组:

SELECT AVG(G1) AS G1,
       AVG(G2) AS G2,
       (AVG(G1) + AVG(G2)) AS Total,
       (AVG(G1) + AVG(G2))/2 AS Average
FROM StudentsTbl
GROUP BY ID

答案 1 :(得分:1)

如果那些是int,你需要施放它们

declare @t table (ID int, G1 int, G2 int); 
insert into @t values 
       (01, 8,  9)  
     , (01, 9, 10) 
     , (01, 7,  8)   
     , (02, 6,  8)  
     , (02, 9, 10) 
     , (03, 9, 10)  
     , (03, 7,  6)   
     , (03, 8,  9)   
     , (03, 7,  8);
with cte as 
( SELECT id
       , AVG(cast(G1 as smallmoney)) AS G1
       , AVG(cast(G2 as smallmoney)) AS G2
   FROM @t
  GROUP BY ID 
)
select *
    , (G1 + G2) as TOTAL  
    , (G1 + G2)/2 as AVERAGE  
from cte
order by id;