我在SQL Server 2000表中有一个名为student
的表,用于存储不同科目的学生标记,看起来像
name | English | Math | Science
--------------------------------
Ram | 80 | 70 | 85
shyam| 70 | 80 | 65
Hari | 80 | 60 | 90
现在我想要根据每个学生的主题将结果分为3列,其中包含名称,主题和标记以及标记列的降序顺序
name | Subject | marks
------------------------
Ram | Science | 85
Ram | english | 80
Ram | math | 70
shyam | math | 80
shyam | english | 70
shyam | Science | 65
Hari | Science | 90
Hari | english | 80
Hari | math | 60
我尝试了很多但没有成功。所以我寻求帮助。谢谢
答案 0 :(得分:2)
你可以用这种方式表达你的表格
SELECT name,
subject,
CASE subject
WHEN 'english' THEN english
WHEN 'math' THEN math
WHEN 'science' THEN science
END marks
FROM student s CROSS JOIN
(
SELECT 'english' subject UNION ALL
SELECT 'math' UNION ALL
SELECT 'science'
) t
ORDER BY name, marks DESC
输出:
| NAME | SUBJECT | MARKS | |-------|---------|-------| | Hari | science | 90 | | Hari | english | 80 | | Hari | math | 60 | | Ram | science | 85 | | Ram | english | 80 | | Ram | math | 70 | | shyam | math | 80 | | shyam | english | 70 | | shyam | science | 65 |
这是 SQLFiddle 演示
答案 1 :(得分:0)
试试这个:
SELECT name, grad as subject, mark
FROM
(
SELECT name, english as mark, 'english' as grad FROM student
UNION
SELECT name, math, 'math' FROM student
UNION
SELECT name, nepali, 'nepali' FROM student
) as t
ORDER BY name, mark DESC
在这里查看小提琴:http://sqlfiddle.com/#!2/17dd2/3
但请记住,你的桌面设计不好。你应该有一个学生桌子和一个带有毕业生(数学,英语等)的表格,另一个表格是那两个带标记的N-m关系。