问题
I have a SQL SELECT Statement situation as follows:
I want to select and get the row with Aquila's Test2 mark which is 30 as the last value under the mark column and omit the null rows. In other words, I want to group the students by Test# and select the latest test mark that is not null. Data should be Sorted by Test# DESC Order.
How do I achieve this? Please help.
My table looks like this:
+------------+-------------+
ID| Test# | Student | Mark |
+------------+-------------+
1 | Test1 | Aquila | 20 |
2 | Test1 | Peter | 30 |
3 | Test1 | Jack | 40 |
4 | Test2 | Aquila | 30 |
5 | Test2 | PETER | 40 |
6 | Test2 | Jack | 50 |
7 | Test3 | Aquila | NULL |
8 | Test3 | Peter | 50 |
9 | Test3 | Jack | 60 |
+------------+-------------+
I want the output to be:
+------------+-------------+
ID| Test# | Student | Mark |
+------------+-------------+
4 | Test2 | Aquila | 30 |
8 | Test3 | Peter | 50 |
9 | Test3 | Jack | 60 |
+------------+-------------+
回答1:
Select * from Students
where Mark is not NULL
order by Mark desc
//the desc order by assumes knowledge of the data
回答2:
I finally worked out the select statement myself as follows and it worked. If someone out there has a similar problem, here is the working code.
SELECT * FROM table
WHERE ID IN (
SELECT MAX(ID)
FROM table WHERE mark IS NOT NULL
GROUP BY Test# DESC);
来源:https://stackoverflow.com/questions/54655055/selecting-last-value-in-a-colum-without-null-value