我想使用与上一个分类帐
相同的accountid从表中检索最后一行的余额|---ledgerid---|--accountid--|--blance--|
| 1 | 1 | 500 |
| 2 | 1 | 800 |
我希望输出为
|---ledgerid---|--accountid--|--blance--|
| 2 | 1 | 800 |
答案 0 :(得分:1)
尝试使用分区,如下所示。
select * from(select *
,row_number()over(partition by accountid order by ledgerid desc) r
from
[yourtable])
where r=1
order by accountid
以上查询适用于SQL Server。
答案 1 :(得分:1)
您可以根据accountid
和ledgerid
的降序给出行号。
<强>查询强>
select t2.`ledgerid`,
t2.`accountid`,
t2.`blance`
from (
select `ledgerid`,
`accountid`,
`blance`, (
case `accountid`
when @curA
then @curRow := @curRow + 1
else @curRow := 1 and @curA := `accountid` end
) as `rn`
from `your_table_name` t,
(select @curRow := 0, @curA := '') r
order by `accountid`, `ledgerid` desc
)t2
where t2.`rn` = 1;
<强> Find demo here 强>
答案 2 :(得分:0)
如果您的分类帐ID继续递增1,那么您可以使用以下查询来获取最后一行:------
SELECT TOP 1 * FROM Table ORDER BY LEDGERID DESC
OR
SELECT * FROM TABLE ORDER BY LEDGERID DESC LIMIT 1
答案 3 :(得分:0)
试试这个: -
select * from table_name where accountid=1 order by legerid desc limit 1
答案 4 :(得分:0)
SELECT l1.* FROM ledger l1 LEFT JOIN ledger l2 ON
(l1.accountid = l2.accountid AND l1.ledgerid < l2.ledgerid)
WHERE l2.ledgerid IS NULL