SQL关于如何同时比较查询中的两个列值



我需要创建一个查询,以查找驱动程序的名称,其考试得分在参加更多考试时会变得较低。所以我有以下表:

branch(branch_id, branch_name, branch_addr, branch_city, branch_phone);
driver(driver_ssn, driver_name, driver_addr, driver_city, driver_birthdate, driver_phone);
license(license_no, driver_ssn, license_type, license_class, license_expiry, issue_date, branch_id);
exam(driver_ssn, branch_id, exam_date, exam_type, exam_score);

**考试是一个日期

所以我正在使用桌子驱动程序和考试。我想以某种方式检查exam_date>另一个date,同时检查该考试

*编辑

这是我想到的,但我觉得某些语法是非法的。我一直遇到语法错误。

s.executeQuery("SELECT driver_name " +
"FROM driver " +
"WHERE driver.driver_ssn IN " +
"(SELECT e1.driver_ssn" +
"FROM exam e1" +
"WHERE e1.exam_score < " +
"(SELECT e2.exam_score FROM exam e2)" +
"AND e1.exam_date > " +
"(SELECT e2.exam_date FROM exam e2)");

编辑!我让它起作用!谢谢大家的输入!

SELECT driver.driver_name 
FROM driver
WHERE driver.driver_ssn IN
    (SELECT e1.driver_ssn 
    FROM exam e1, exam e2, driver d 
    WHERE e1.exam_score < e2.exam_score
    AND e1.exam_date > e2.exam_date 
    AND e1.driver_ssn=e2.driver_ssn)

您需要进行自我加入。请参阅此示例并将其用于您的模式。

select d.name, 
       es.date_taken as 'prev date', 
       es.score as 'prev score',
       es.date_taken as 'new date', 
       es_newer.score as 'new score'
  from driver d
         inner join exam_score es
           on d.id = es.driver_id
         left outer join exam_score es_newer
           on d.id = es_newer.driver_id 
          and es_newer.date_taken > es.date_taken
          and es_newer.score < es.score
 where es_newer.id is not null

这是我要演示的SQL小提琴。

选择返回一组,您无法将单个值与集合进行比较。您可以尝试使用这些线路。这类似于您的,并且不处理三个考试案例: -

SELECT driver_name 
  FROM driver
  JOIN exam e1 ON driver_ssn
  JOIN exam e2 ON driver_ssn
 WHERE e1.exam_score < e2.exam_score
   AND e1.exam_date > e2.exam_date

查询选择了驱动程序所参加的所有考试对,其中得分较少,日期big

对此问题的简单采取的措施是让驾驶员参加几次考试,第二个得分较低。

比较来自同一表SQL使用自加入的列。您的加入条件应包括:

select e1.driver_ssn, e1.exam_type, e1.exam_score as score_before, 
       e2.exam_score as score_after
exam e1 join exam e2 on (e1.driver_ssn = e2.driver_ssn and 
                    e1.exam_type = e2.exam_type and
                    e1.exam_date < e2.exam_date and 
                    e1.exam_score > e2.exam_score)

相关内容

  • 没有找到相关文章

最新更新