我的表格如下http://sqlfiddle.com/#!9/a09f7
| transid | artid | number | balance | date |
|---------|--------|--------|---------|----------------------------|
| 1 | GJ220 | 10 | 10 | February, 27 2015 08:51:57 |
| 2 | PJ25x8 | 9 | 9 | February, 27 2015 06:51:57 |
| 3 | GJ220 | 10 | 20 | February, 27 2015 09:51:57 |
| 4 | PJ25x8 | -4 | 5 | February, 27 2015 10:51:57 |
| 5 | GJ220 | -10 | 10 | February, 27 2015 07:51:57 |
我的目标是找到每个月为每篇文章完成的最后一笔交易并获得余额。如果那个月没有完成交易,它应该报告前一个月的价值。
此外,未来它应该能够将查询限制为特定年份
答案 0 :(得分:0)
试试这个:
select *from `log`
where DATE_FORMAT(`date`, "%m-%Y") = "02-2015"
group by `artid`
order by `date` desc;
这是你的基本想法。希望你找到你的记录。 您需要选择月份并获取特定月份的记录。
您还可以计算余额总和,如:
select `transid`,`artid`,`number`, sum(`balance`) as `balance`,`date` from `log`
where DATE_FORMAT(`date`, "%m-%Y") = "02-2015"
group by `artid`
order by `date` desc;
答案 1 :(得分:0)
以下是根据需要提供输出的查询:
select * from log
where transid IN
(select max(transid) from log
group by artid,`date`
order by transid desc);