1

我是 SQL 新手(初级程序员),所以如果这看起来像一个简单的问题,我深表歉意。我正在尝试在我的网站上创建一个表格,显示最低 10 年级以及有关学生的一些信息。从这方面来说我很舒服,但是我在编写写 SQL 查询时遇到了麻烦。我正在使用 SQL Server 2008。

我的数据库中有一个包含 10 列和 500 行的表。其中两列包含等级(等级 1 和等级 2)。我的目标是在我的网站表格中显示前 10 个最低 GRADE1,但如果 GRADE1 为 NULL,我希望它考虑 GRADE2 并改为显示它。因此,在上下文中,如果一个名为 Billy 的学生没有 GRADE1(其为 NULL),但他的 GRADE2 是所有学生中最低的(GRADE1 和 GRADE2 的组合),那么他应该是列表中的第一位。

我非常感谢帮助制作能够完成此任务的查询,我一直在研究解决方案,但它只会让我更加困惑。

4

5 回答 5

1

在您想要使用的 SQL Server 中isNull()

SELECT TOP 10 isNull(grade1,grade2) AS `Grade`
FROM mytable
ORDER BY Grade DESC
于 2013-03-08T19:16:16.470 回答
1

您可以在 order by 子句中使用 case

select top 10 * 
from students 
order by case when grade1 is null then grade2 else grade1 end desc

编辑

在 BillyCode 评论只包括那些在表中出现 3 次或更多次的学生之后,我建议这样做

select top 10 s.*  
from students s
inner join (select StudentId, Count(*) as total from students) c on s.StudentId = c.StudentId  
where c.total >= 3
order by case when grade1 is null then grade2 else grade1 end desc

但我不确定您是否可以加入子查询。

于 2013-03-08T19:17:43.103 回答
0

COALESCE功能可以满足您的需求。如果不为空或为空,COALESCE(GRADE1, GRADE2)将显示。GRADE1GRADE2GRADE1

所以代替ORDER BY GRADE1, 你可以做ORDER BY COALESCE(GRADE1, GRADE2)

有关COALESCE. _

于 2013-03-08T19:13:22.500 回答
0

试试这个:

select Top 10 
student , (case when grade1 is null then grade2 else grade1 end ) as g1 , grade2 as g2 from table order by g1 desc
于 2013-03-08T19:16:41.007 回答
0

另一种方法是先找出成绩最低的 10 名学生。将grade1重命名为grade。然后找出成绩最低的 10 名学生2。将grade2重命名为grade。之后联合这两个结果。从那里,找到成绩最低的 10 名学生。SQL 类似于:

SELECT id, grade
FROM   (SELECT   id, grade1 AS grade
        FROM     students
        ORDER BY grade1 DESC
        LIMIT 10
        UNION
        SELECT   id, grade2 AS grade
        FROM     students
        ORDER BY grade2 DESC
        LIMIT 10)
ORDER BY grade DESC
LIMIT 10
于 2013-03-09T16:04:58.593 回答