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

问题描述 投票:2回答:2

我有一张学生表,他们的分数由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
sql sql-server
2个回答
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;

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
© www.soinside.com 2019 - 2024. All rights reserved.