lastReports
子查询本身返回10行。 “包装器”记录确实存在,但是当我加入它们时,我得到0 rows returned in 12ms from:
在SQLite上。
我的加入很好,我没有犯选择错误(SQL LEFT JOIN Subquery Alias)……我想念的是什么,还是不明白?
SELECT
name
FROM
teachers
INNER JOIN (SELECT
teacher_id,
reportingPeriod,
ReportingType,
date('now') - 3 as AgeOfReport,
count(id) as NumberOf
FROM
reports
GROUP BY
teacher_id
ORDER BY
teacher_id ASC,
reportingPeriod asc
) AS lastReports
ON teachers.id = lastReports.teacher_id;
SAMPLE DATA
TEACHERS
ID NAME
-----------------
1 Mr John Smith
2 Ms Janet Smith
REPORTS
---------------------------------------------------
ID TEACHER_ID REPORTINGPERIOD REPORTINGTYPE
1 1 Jan 2017 Draft
2 1 Feb 2017 Draft
3 2 Jun 2018 Draft
4 2 Jul 2018 Draft
5 1 Mar 2017 Final
DESIRED RESULTS
------------------
Mr John Smith Final Mar 2017
Ms Janet Smith Draft Jul 2018
答案 0 :(得分:1)
您可以尝试按row_number
列创建TEACHER_ID
并按REPORTINGPERIOD
进行排序,这意味着在子查询中更接近日期,获得rn = 1
每个{{1 }}最大日期和TEACHER_ID
上的JOIN
。
TEACHERS
查询1 :
CREATE TABLE TEACHERS(
ID INT,
NAME VARCHAR(50)
);
INSERT INTO TEACHERS VALUES (1, 'Mr John Smith');
INSERT INTO TEACHERS VALUES (2, 'Ms Janet Smith');
CREATE TABLE REPORTS(
ID INT,
TEACHER_ID int,
REPORTINGPERIOD DATE,
REPORTINGTYPE varchar(100)
);
INSERT INTO REPORTS VALUES (1,1,'Jan 2017', 'Draft');
INSERT INTO REPORTS VALUES (2,1,'Feb 2017', 'Draft');
INSERT INTO REPORTS VALUES (3,2,'Jun 2018', 'Draft');
INSERT INTO REPORTS VALUES (4,2,'Jul 2018', 'Draft');
INSERT INTO REPORTS VALUES (5,1,'Mar 2017', 'Final');
Results :
SELECT t.NAME,
t1.REPORTINGTYPE,
t1.REPORTINGPERIOD
FROM teachers as t INNER JOIN
(
SELECT *,(SELECT COUNT(*) FROM REPORTS tt WHERE tt.TEACHER_ID = t1.TEACHER_ID and tt.REPORTINGPERIOD>=t1.REPORTINGPERIOD) rn
FROM REPORTS t1
) as t1 on t1.TEACHER_ID = t.id and rn = 1
ORDER BY t.NAME
答案 1 :(得分:0)
REPORTINGPERIOD
的值不能正确比较,因为Jul
在字母表中的Jun
之前。您应该使用yyyy-mm
之类的格式,其中最重要的字段在前。
在SQLite中,您可以简单地use MAX() to select entire rows:
SELECT t.Name,
r.ReportingType,
max(r.ReportingPeriod)
FROM Teachers t
JOIN Reports r ON t.ID = r.Teacher_ID
GROUP BY r.Teacher_ID;
NAME REPORTINGTYPE max(r.ReportingPeriod)
-------------- ------------- ----------------------
Mr John Smith Final 2017-03
Ms Janet Smith Draft 2018-07