这是当前表中的所有数据
SELECT
id,harga,kode_tahun_ajaran
FROM
tblharga
+----+---------+-------------------+
| id | harga | kode_tahun_ajaran |
+----+---------+-------------------+
| 1 | 400000 | THN2018/2019 |
| 2 | 50000 | THN2018/2019 |
| 3 | 1000000 | THN2018/2019 |
| 4 | 900000 | THN2018/2019 |
| 5 | 500000 | THN2017/2018 |
| 6 | 600000 | THN2018/2019 |
+----+---------+-------------------+
并且我运行此代码以分组 kode_tahun_ajaran 来获取最后一个 harga
SELECT
id,harga,kode_tahun_ajaran
FROM
tblharga
GROUP BY
kode_tahun_ajaran
ORDER BY id DESC
+----+--------+-------------------+
| id | harga | kode_tahun_ajaran |
+----+--------+-------------------+
| 5 | 500000 | THN2017/2018 |
| 1 | 400000 | THN2018/2019 |
+----+--------+-------------------+
harga 列应获取最后的600000数据,这是由于 order by 代码所致。< / p>
如何通过另一种方式对最新数据进行分组? 预先感谢。
答案 0 :(得分:1)
您可以在下面尝试
SELECT
id,harga,kode_tahun_ajaran
FROM
tblharga where id in (select max(id) from tblharga group by kode_tahun_ajaran)
答案 1 :(得分:0)
select id,S.kode_tahun_ajaran,harga
from tblharga S inner join
( select kode_tahun_ajaran,max(id) maxid from tblharga group by kode_tahun_ajaran) T
where T.kode_tahun_ajaran=S.kode_tahun_ajaran and maxid=id;