如何在SQL语句中选择最后一个条目满足where条件变量的行?

时间:2019-07-02 22:04:13

标签: sql

我有一张表格,其中包含学生的所有最新考试日期以及他们正在参加的考试的类型。

类似以下内容:

联接表

+--------------+--------+--------+
|     Name     |  Test  |  Date  |
+--------------+--------+--------+
| Test Taker A | Math   | May 9  |
| Test Taker B | Math   | May 9  |
| Test Taker A | Math 2 | May 10 |
| Test Taker C | Math   | May 8  |
| Test Taker A | Spanish| May 12 |
+--------------+--------+--------+    

+----------------+---------+-------+
|Registration-ID | Name ID |Test Id|
+----------------+---------+-------+
| 1              | 453     |134534 | 
| 2              | 34534   |134534 |
| 3              | 2343    |134534 | 
| 4              | 453     |12343  |
| 5              | 453     | 4531  |
+--------------+-----------+-------+
+--------------+--------+----+
|Roster  Name  | Name ID|demo|
+--------------+--------+----+
| Test Taker A | 453    | M  |
| Test Taker B | 34534  | F  |
| Test Taker C | 2343   | M  |
+--------------+--------+----+   
+---------+---------+--------+
|Test Name| test ID |Session |
+---------+---------+--------+
| Spanish | 4531    | 3      |
| Math    | 134534  | 2      |
| Math2   | 12343   | 4      |
| Math    | 134534  | 1      |
+---------+---------+--------+   

+------------+-------+
|   Session  |  Date |
+--------------------+
| 2          |  May 9|
| 2          | May 9 |
| 4          | May 10|
| 1          | May 8 |
| 3          |May 12 |
+------------+-------+

现在我有

select R.Name, T.Test, D.Date 
from Roster ro
    join registration re on re.name = ro.name
    join test t on t.test_id = re.test_id
    join date d on d.session = t.session
where t.Test = "Math".

这将给我考生A,B,C。但是我希望结果显示Tester B和C,因为他们上次进行的测试是Math。仅当该人最后一次接受测试且没有其他条目时,我才想要结果。

不好意思的表格表示歉意,不确定如何格式化。

1 个答案:

答案 0 :(得分:0)

我建议在您的not exists子句中使用where和一个相关的子查询,以尝试为 same 的应试者寻求一个后来的测试。 不是 Math,例如:

select ro.Name, t.Test, d.Date 
from 
    Roster ro
    join registration re on re.name = ro.name
    join test t on t.test_id = re.test_id
    join date d on d.session = t.session
where 
    t.Test = 'Math' and not exists
    (
        select 1
        from 
            Roster ro2
            join registration re2 on re2.name = ro2.name
            join test t2 on t2.test_id = re2.test_id
            join date d2 on d2.session = t2.session
        where
            ro2.name = ro.name and
            t2.test <> 'Math' and 
            d2.date > d.date
    )

我相信您的原始代码中有一个错字,因为没有别名r(用于select子句),并且您还加入了别名ro,但别名也没有“不存在。