复杂SQL查询 - 嵌套查询

时间:2013-05-09 13:58:31

标签: sql sqlite nested-query

这是job_form表...

job_num  | name | address |
---------+------+---------+
 1       | Tom  | Smith   |
 2       | John | Doe     |
 3       | Max  | Smith   |

这是individual_job表...

job_num  | date       | description   |
---------+------+---------------------+
 1       | 23-01-2012 | Eat food      |
 1       | 24-01-2012 | Do dishes     |
 1       | 25-01-2012 | Sweep floor   |
 ...     | ...        | ...           |
 2       | 19-05-2013 | Play games    |
 2       | 23-05-2013 | Do code       |
 2       | 27-05-2013 | Sleep         |
 ...     | ...        | ...           |
 3       | 23-05-2013 | Eat food      |
 3       | 24-05-2013 | Do dishes     |
 3       | 25-05-2013 | Sweep floor   |
 ...     | ...        | ...           |

我想创建一个查询,为每个job_form抽出一行,其中包括要完成的第一个作业的日期,要完成的上一个作业的日期以及上面列出的作业总数表格。查询需要仅显示具有需要在将来完成的作业的作业表单。

示例是:

job_num  |  first_job_date  |  last_job_date  |  count_of_jobs  |  name
---------+------------------+-----------------+-----------------+-------------
2        |  19-05-2013      |  27-05-2013     |  3              |  John
3        |  23-05-2013      |  25-05-2013     |  3              |  Max

我几年没有做过SQL,这个让我完全难过。我知道我必须做一个嵌套查询,但无法解决订单......

任何帮助都非常感激。

更新为在结果中包含名称列(忘记了这一点,抱歉)

2 个答案:

答案 0 :(得分:3)

这是一个简单的聚合查询:

select ij.job_num,
       min(ij.date) as first_job_date,
       max(ij.date) as last_job_date, count(*) as count_of_jobs
from individual_job ij
group by ij.job_num

对于将来的工作,您需要进行日期比较,如下所示(取决于数据库):

where date >= sysdate

where date >= now()

where date >= getdate()

where子句位于from子句之后。

答案 1 :(得分:0)

修改根据Gordon的说法,如果您不需要任何job_form个特定字段,则无需加入。但是,如果你这样做(例如姓名或地址),那么:

SELECT jf.job_id,
       jf.name, 
       MIN(ij.date) AS first_job_date, 
       MAX(ij.date) as last_job_date, 
       COUNT(*) as count_of_jobs
FROM job_form jf
  INNER JOIN individual_job ij
    ON jf.job_num = ij.job_num
GROUP BY jf.job_id, jf.name -- i.e. non-aggregated select fields here