我有一个表包含三个考试的标记,一个主题每个标记在不同栏目中如何从三列中选择最佳两个标记?
答案 0 :(得分:4)
这将是可怕的 - 尝试:
select case when mark1 >= mark2 and mark1 >= mark3 then mark1
when mark2 >= mark1 and mark2 >= mark3 then mark2
else mark3 end as first,
case when mark1 >= mark2 and mark1 <= mark3 then mark1
when mark1 >= mark3 and mark1 >= mark2 then mark1
when mark2 >= mark1 and mark1 >= mark3 then mark2
when mark2 >= mark3 and mark1 >= mark1 then mark2
else mark3 end as second
from my_table;
这将教会您将来将每个标记存储在一个单独的行中; - )
答案 1 :(得分:1)
首先,你应该真正规范化表格。第二,为了单个查询的目的,有一种简单的规范化方法:CTE。
BEGIN;
CREATE SCHEMA sogrades;
SET search_path TO sogrades;
CREATE DOMAIN grade AS
INT
CHECK (VALUE BETWEEN 1 AND 5)
;
CREATE TABLE grades (
student INT NOT NULL PRIMARY KEY
, grade1 GRADE
, grade2 GRADE
, grade3 GRADE
);
INSERT INTO grades (student, grade1, grade2, grade3)
VALUES
(10, 1, 3, 5)
, (20, 4, 3, 2)
, (30, 1, 2, 1)
;
WITH g (student, grade) AS (
SELECT student, grade1 FROM grades UNION
SELECT student, grade2 FROM grades UNION
SELECT student, grade3 FROM grades
)
SELECT DISTINCT gl.student, gl.grade
FROM g gl, g gr
WHERE gl.student = gr.student
AND gl.grade < gr.grade
ORDER BY student, grade;
ROLLBACK;