我想在过去2个月内select * from Table TRAINEE
+前一个REPORT.DATE
。
TRAINEE
+----+----------+
| ID | NAME |
+----+----------+
| 1 | John Doe |
+----+----------+
| 2 | Jane Doe |
+----+----------+
REPORT
+------------+------------+---------------+
| TRAINEE_ID | DATE | REPORT |
+------------+------------+---------------+
| 1 | 01.07.2018 | Not Important |
+------------+------------+---------------+
| 1 | 02.07.2018 | Not Important |
+------------+------------+---------------+
| 1 | 03.07.2018 | Not Important |
+------------+------------+---------------+
| 2 | 02.07.2018 | Not Important |
+------------+------------+---------------+
| 2 | 02.07.2018 | Not Important |
+------------+------------+---------------+
| 2 | 03.07.2018 | Not Important |
+------------+------------+---------------+
Wanted results
+----+----------+--------------+
| ID | NAME | FIRST_REPORT |
+----+----------+--------------+
| 1 | John Doe | 01.07.2018 |
+----+----------+--------------+
| 2 | Jane Doe | 02.07.2018 |
+----+----------+--------------+
我已经尝试过...
通过这种方式,我只给我一行带日期,其余的行用NULL
填充,因为联接仅返回一行。删除ROWNUM
过滤器将使我的查询为TRAINEE
中发现的每一行返回一行REPORT
。所以这也不行。我必须在哪里放置ROWNUM
过滤器?
SELECT
TRAINEE.*,
OUTER_ORDER_DATE.DATE
FROM
Trainee
LEFT JOIN
(
SELECT
DATE,
ID,
ROWNUM as rnum
FROM
(
SELECT
DATE,
ID,
FROM
REPORT INNER_ORDER_DATE
WHERE
INNER_ORDER_DATE.DATE >= add_months(sysdate,-2)
ORDER BY
INNER_ORDER_DATE.DATE ASC
)
WHERE
rnum < 2
) ON OUTER_ORDER_DATE ON OUTER_ORDER_DATE.ID = a.ID
然后,我尝试了以下查询,该查询的语法有些错误;内部查询无法访问外部查询的Trainee.ID
。
SELECT
Trainee.*,
(SELECT
DATE
FROM (
SELECT
DATE
FROM
REPORT
WHERE
ID = TRAINEE.ID
AND
DATE >= add_months(sysdate,-2)
ORDER BY
DATE ASC
)
WHERE
ROWNUM < 2
) as DATE
FROM
TRAINEE
要使所需的结果在上方,我的查询应该是什么样的?
如果这个问题已经回答,请给我链接。我不知道如何搜索这种情况。谢谢。
答案 0 :(得分:3)
您应该尝试使用以下代码:
SELECT trainee.id, trainee.name, report.report_date
FROM trainee
JOIN ( SELECT trainee_id, MIN (report_date) AS report_date
FROM report
WHERE report_date >= ADD_MONTHS (SYSDATE, -2)
GROUP BY trainee_id) report
ON (report.trainee_id = trainee.id)
答案 1 :(得分:0)
尝试一下:
select t.id, t.name, min(r.date) firstdate
from trainee t, report r
where t.id = r.id
and r.date >= add_months(sysdate,-2)