我需要从下表中获取每个指标名称的最新记录,例如2015-11-16的数据GI和2015-11-14的GO。
我怎样才能做到这一点?
由于
答案 0 :(得分:2)
有很多方法可以实现这一目标,称为group wise maximum
https://dev.mysql.com/doc/refman/5.7/en/example-maximum-column-group-row.html
select t1.* from table_name t1
join (
select indicator_name,max(indicator_date) as indicator_date from table_name
group by indicator_name
)t2
on t1.indicator_name = t2.indicator_name
and t1.indicator_date = t2.indicator_date
答案 1 :(得分:1)
如果您想要每个indicator_name
的最新行,那么您可以按indicator_name
为每个行组分配一个行号,并按indicator_date
按降序排序。
<强>查询强>
select t1.indicator_id,
t1.indicator_name,
t1.indicator_value,
t1.indicator_date
from
(
select indicator_id,
indicator_name,
indicator_value,
indicator_date,
(
case indicator_name when @curA
then @curRow := @curRow + 1
else @curRow := 1 and @curA := indicator_name end
) + 1 as rn
from tblIndicators t,
(select @curRow := 0, @curA := '') r
order by indicator_name,indicator_date desc
)t1
where t1.rn = 1;
答案 2 :(得分:0)
SELECT * from yourtable
GROUP BY indicator_name
ORDER BY indicator_date DESC
答案 3 :(得分:0)
试试这个......
SELECT * FROM table_name ORDER BY indicator_name,indicator_date DESC