简体   繁体   English

如何在MySQL查询中获取GROUP BY的最新索引?

[英]How to get latest index of GROUP BY in mysql query?

I got confused about the algorithm and way to get the latest index of Group by. 我对获取Group by的最新索引的算法和方法感到困惑。 I have a query like this. 我有这样的查询。

SELECT hasil_kmbg AS RESULT,
   EXTRACT(MONTH
           FROM tgl_check) AS MONTH,
   EXTRACT(YEAR
           FROM tgl_check) AS YEAR
FROM perkembangan
WHERE no_pasien=11
GROUP BY MONTH,
         id_kmbg DESC

and here is result of the query 这是查询的结果

|Result|Month|Year|
-------------------
|3     |1    |2013|
|1     |1    |2013|
|5     |1    |2013|
|1     |2    |2013|
|1     |3    |2013|
and so on

the question is, how I just get Result which is Result is 3 in Month 1? 问题是,我如何获取结果,即第1个月的结果是3? I didn't want to show other result int Month 1 except 3 (the latest, I order it by desc). 我不想在第1个月中显示除3以外的其他结果(最新的结果是我按desc排序)。

You are getting multiple rows per month because you have included id_kmbg in the group by clause. 由于您在group by子句中包含了id_kmbg ,因此您每月id_kmbg多行。 I think you want the max() function: 我想你想要max()函数:

select max(hasil_kmbg) as Result, EXTRACT(MONTH FROM tgl_check) as Month,
       EXTRACT(YEAR FROM tgl_check) as Year
from perkembangan
where no_pasien=11
group by Month, Year;

I think that you are looking for this: 我认为您正在寻找:

SELECT hasil_kmbg AS RESULT,
       EXTRACT(MONTH
               FROM tgl_check) AS MONTH,
       EXTRACT(YEAR
               FROM tgl_check) AS YEAR
FROM perkembangan
WHERE no_pasien=11
ORDER BY id_kmbg DESC
LIMIT 1

My hunch is that you don't need the GROUP BY here (since you are ordering by ID DESC). 我的直觉是您在这里不需要GROUP BY(因为您是通过ID DESC订购)。

If you need a group by, you might need to rework how you select hasil_kmbg. 如果需要分组依据,则可能需要重新选择hasil_kmbg的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM