sql查询对五列中最少的两列中的值求和

时间:2017-11-22 15:05:35

标签: sql sqlite

名为“StudentResults”的数据库表存储学生主题测试的结果。这些测试根据性能进行评分。所以有数学成绩,法语成绩,英语成绩,科学成绩和农业科学成绩等级。我想创建一个查询,检查并总结来自整个五个不同结果的两个最小结果。 john maths = 40 french = 50 english = 60 science = 30 agric = 70.在五项主题测试中,两项结果最少,分别为30和40。我如何编写一个查询来总结它们。表格示例如下:

  

|名称|数学|法语|英语|科学|农业|   Two_Least |
  -------------------------------------------------- -------------------------------------
|詹姆斯| 30.0   | 50.0 | 70.0   | 10.0 | 70.0 | 40.0   |
| joshie | 10.0   | 30.0 | 40.0   | 10.0 | 70.0 | 20.0   |
| janete | 20.0   | 60.0 | 70.0   | 80.0 | 90.0 | 80.0 |



詹姆斯至少两个是数学= 30科学= 10. Two_Least = 40
joshie两个最少是数学= 10科学= 10. Two_Leats = 20
janete至少两个是数学= 20法国人= 60. Two_Least = 80

请问我如何编写一个SQL查询来解决这个问题。非常感谢你们。

3 个答案:

答案 0 :(得分:2)

我使用的是SQL ServerOracle 12c

SELECT t.*, s.two_least
FROM t
CROSS APPLY (SELECT SUM(val)
             FROM (
               SELECT ROW_NUMBER() OVER (ORDER BY z.val) AS rn, z.val
               FROM (
                 SELECT t.Maths UNION ALL       --FROM dual
                 SELECT t.French UNION ALL
                 SELECT t.English UNION ALL
                 SELECT t.Science UNION ALL
                 SELECT t.Agric
                 ) z(val)
              ) v
              WHERE rn IN (1,2)
           ) s(two_least);

<强> Rextester Demo

SQLite版本(应通过某种id进行关联):

SELECT *, MIN(Maths, French, English, Science, Agric) + 
( SELECT  Maths AS s FROM t t2 WHERE t.Name = t2.Name UNION ALL 
  SELECT  French     FROM t t2 WHERE t.Name = t2.Name UNION ALL
  SELECT  English    FROM t t2 WHERE t.Name = t2.Name UNION ALL
  SELECT  Science    FROM t t2 WHERE t.Name = t2.Name UNION ALL
  SELECT  Agric      FROM t t2 WHERE t.Name = t2.Name
  ORDER BY s LIMIT 1,1
) AS result
FROM t;

<强> DBFiddle Demo

正确的方法:规范您的架构。

答案 1 :(得分:1)

如果这是我的选择 - 我有一个单独的表,即 - 等级(StudentId,Class,Grade)是表2,而Student(StudentId,Name) - 它会使查询事情变得更容易。< / p>

Lad的解决方案对你有用,但重组表似乎很明智。

答案 2 :(得分:1)

我找到了将其更新为真实列的方法。其..

String sql = "update t set Agregate=(SELECT MIN(Maths,French,English,Science,Agric) + " +
"( SELECT  Maths AS s FROM t t2 WHERE t.ID = t2.ID UNION ALL " +
"  SELECT  French FROM t t2 WHERE t.ID = t2.ID UNION ALL" +
"  SELECT  English FROM t t2 WHERE t.ID = t2.ID UNION ALL" +
"  SELECT  Science FROM t t2 WHERE t.ID = t2.ID UNION ALL" +
"  SELECT  Agric FROM t t2 WHERE t.ID = t2.ID" +
"  ORDER BY s LIMIT 1,1" +
") AS result WHERE ID = t.ID
非常感谢我的老板们。我非常感谢每一个人的努力。谢谢@ lad2025。