sql 查询以获取与当前记录日期相比的最大日期值
sql query to get value on maximum date comparing current record date
我有2张桌子
具有字段
的表 1
childid, ondate, points
1 31/01/2017 50
1 28/02/2017 77
1 31/03/2017 25
具有字段
的表 2
childid, programid, fromdate
1 1 01/01/2017
1 2 01/03/2017
Table2 指定 child 从 01/01/2017 到 01/03/2017 在 programid 1 中,之后他在 programid 2 中。
所以我的结果应该是
childid, ondate, points Programid
1 31/01/2017 50 1
1 28/02/2017 77 1
1 31/03/2017 25 2
请帮忙
试试这个:
SELECT t1.childid, t1.ondate, t1.points, t2.programid
FROM table1 as t1
INNER JOIN table2 as t2 on t1.chilid = t2.childid
and t2.fromdate <= t1.ondate;
只需用 t2.fromdate <= t1.ondate
连接两个表即可。
注意:此答案适用于 MySQL。
这有点棘手。我认为相关子查询是最简单的方法:
select t1.*,
(select t2.programid
from table2 t2
where t2.childid = t1.childid and
t2.fromdate <= t1.ondate
order by t1.ondate desc
limit 1
) as programid
from table1 t1
order by t1.ondate desc;
这保证在 table1
.
的任何给定日期只有一个节目(每个 child)
如果查询需要与 VFP 兼容,则可以是:
Select tb1.*, tb2.programid ;
FROM table1 tb1 ;
inner Join (;
SELECT *, ;
NVL((Select Min(fromdate) ;
from table2 t1;
WHERE t1.childid=t2.childid And ;
t1.fromdate > t2.fromdate),Date(9999,12,31)) As toDate ;
FROM table2 t2 ;
) tb2 ;
ON tb1.childid = tb2.childid And ;
tb1.ondate >= tb2.fromdate And ;
tb1.ondate < tb2.toDate
我有2张桌子 具有字段
的表 1childid, ondate, points 1 31/01/2017 50 1 28/02/2017 77 1 31/03/2017 25
具有字段
的表 2childid, programid, fromdate 1 1 01/01/2017 1 2 01/03/2017
Table2 指定 child 从 01/01/2017 到 01/03/2017 在 programid 1 中,之后他在 programid 2 中。 所以我的结果应该是
childid, ondate, points Programid 1 31/01/2017 50 1 1 28/02/2017 77 1 1 31/03/2017 25 2
请帮忙
试试这个:
SELECT t1.childid, t1.ondate, t1.points, t2.programid
FROM table1 as t1
INNER JOIN table2 as t2 on t1.chilid = t2.childid
and t2.fromdate <= t1.ondate;
只需用 t2.fromdate <= t1.ondate
连接两个表即可。
注意:此答案适用于 MySQL。
这有点棘手。我认为相关子查询是最简单的方法:
select t1.*,
(select t2.programid
from table2 t2
where t2.childid = t1.childid and
t2.fromdate <= t1.ondate
order by t1.ondate desc
limit 1
) as programid
from table1 t1
order by t1.ondate desc;
这保证在 table1
.
如果查询需要与 VFP 兼容,则可以是:
Select tb1.*, tb2.programid ;
FROM table1 tb1 ;
inner Join (;
SELECT *, ;
NVL((Select Min(fromdate) ;
from table2 t1;
WHERE t1.childid=t2.childid And ;
t1.fromdate > t2.fromdate),Date(9999,12,31)) As toDate ;
FROM table2 t2 ;
) tb2 ;
ON tb1.childid = tb2.childid And ;
tb1.ondate >= tb2.fromdate And ;
tb1.ondate < tb2.toDate