求取10-15条记录的三列的平均值
是一道面试题,本身不难,突破点是在使用临时表。
USE [tempdb] GO --DROP TABLE score CREATE TABLE score(ID INT IDENTITY(1,1) PRIMARY KEY,语文 INT ,数学 int ,英语 int ) GO INSERT INTO score (语文,数学,英语) SELECT 78,45,67 UNION ALL SELECT 49,88,67 UNION ALL SELECT 78,45,45 UNION ALL SELECT 78,56,67 UNION ALL SELECT 45,45,44 UNION ALL SELECT 78,45,67 UNION ALL SELECT 78,85,67 UNION ALL SELECT 24,36,43 UNION ALL SELECT 78,55,67 UNION ALL SELECT 45,45,63 UNION ALL SELECT 78,45,96 UNION ALL SELECT 85,33,84 UNION ALL SELECT 78,85,67 UNION ALL SELECT 99,44,39 UNION ALL SELECT 79,71,82
解答方法一:(临时表)
SELECT * INTO #TEMP FROM score WHERE ID BETWEEN 10 AND 15 ORDER BY ID ASC SELECT AVG(语文) as 语文平均成绩,AVG(数学) AS 数学平均成绩,AVG(英语) as 英语平局成绩 FROM #TEMP
解答方法二:(共用表达式)
WITH CET AS( SELECT * FROM score WHERE ID BETWEEN 10 AND 15 ORDER BY ID ASC ) SELECT AVG(语文) as 语文平均成绩,AVG(数学) AS 数学平均成绩,AVG(英语) as 英语平局成绩
FROM CET
dangran