我有一张表,我需要获取最后12条记录,这些记录按年()月()ASC分组。我尝试使用下面的查询,但结果不符合预期。
SELECT * FROM
(
SELECT
id,
tanggal,
date_format(tanggal,'%b-%Y') as bulan,
sum(sisa_pokok) as jumlah
FROM transaksi_detail
GROUP BY date_format(tanggal,'%b-%Y')
ORDER BY id DESC LIMIT 12
) sub
ORDER BY id ASC
查询结果如下
我的预期结果是按年(),月()按布兰列顺序排序,如下所示
Bulan jumlah
Mar-2018 26600000
Oct-2017 1000000
Sept-2017 4500000
and so on....
答案 0 :(得分:0)
EXTRACT(YEAR FROM bulan) as year
SELECT EXTRACT(YEAR FROM tanggal) as year , EXTRACT(MONTH FROM tanggal) as month, id FROM table_name group by year order by month
你可以获得相同的年份,就像你可以获得一个月之后的组合,并命令我希望它会帮助你
答案 1 :(得分:0)
这适用于我的情况
SELECT * FROM
(
SELECT
id,
tanggal,
month(tanggal),
year(tanggal),
date_format(tanggal,'%b-%Y') as bulan,
sum(sisa_pokok) as jumlah
FROM transaksi_detail
GROUP BY date_format(tanggal,'%b-%Y')
ORDER BY id DESC LIMIT 12
) sub
ORDER BY year(tanggal), month(tanggal) ASC