Here's an example of how you can achieve this:
Table similar to yours
create table tbl_item_code (
id int,
item_code varchar(10),
description varchar(10)
);
insert into tbl_item_code values
(1, 'one', 'one'),
(2, 'two', 'two'),
(3, 'three', 'three');
Lines code table
create table tbl_lines_code (
id_lines_code int,
id int,
dt date,
balance int
);
insert into tbl_lines_code values
(1, 1, '2010-01-01', 100),
(2, 1, '2015-01-01', 200),
(3, 3, '2010-01-01', 500),
(4, 3, '2015-01-01', 600);
Query
select ic.id, ic.item_code, ic.description, maxdt.maxdt, lc.balance
from tbl_item_code ic
left join (
tbl_lines_code lc
inner join (
select id, max(dt) maxdt from tbl_lines_code group by id
) maxdt
on lc.id = maxdt.id
and lc.dt = maxdt.maxdt
) on ic.id = lc.id
Result
| id | item_code | description | maxdt | balance |
|----|-----------|-------------|---------------------------|---------|
| 1 | one | one | January, 01 2015 00:00:00 | 200 |
| 3 | three | three | January, 01 2015 00:00:00 | 600 |
| 2 | two | two | (null) | (null) |
Example: http://sqlfiddle.com/#!9/08c56/7
If you are going to try to get the last of a field you have to group by and thus can not use the *. Try this:
Select i.id_lines_code, i.id, i.no_doc, i.receive, i.issue, i.balance, i.ref,
from tbl_item_code i, Last(l.date) as Last_Updated
left join tbl_lines_code l on i.id = l.id
Group by i.id_lines_code, i.id, i.no_doc, i.receive, i.issue, i.balance, i.ref,
from tbl_item_code i
Order by i.id ASC;
You can achieve by left join twice and comparing the date.
select i.*, maxl.balance, maxl.date
from tbl_item_code i
left join tbl_lines_code maxl on i.id = maxl.id
left join tbl_lines_code l on i.id = l.id on max1.date < l.date
order by i.id asc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.