如何选择数据并获得每个ID的最后余额?

时间:2015-09-18 03:09:26

标签: php sql codeigniter

我想从tbl_item_code中选择所有数据并获取最后一次余额表tbl_lines_code

tbl_item_code

tbl_item_code

tbl_lines_code enter image description here

这是我的sql。

select i.*,l.balance,last(l.date) 
from tbl_item_code i
left join tbl_lines_code l on i.id = l.id
order by i.id ASC

请帮忙。谢谢。

3 个答案:

答案 0 :(得分:1)

以下是如何实现这一目标的示例:

与您类似的表格

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');

行代码表

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);

<强>查询

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

<强>结果

| 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) |

示例:http://sqlfiddle.com/#!9/08c56/7

答案 1 :(得分:0)

如果您要尝试获取最后一个字段,则必须分组,因此无法使用*。试试这个:

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; 

答案 2 :(得分:0)

您可以通过左连接两次并比较日期来实现。

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