我的 MySQL 查询有问题,问题是我有下表:
id, rep, val dates
1 rep1 200 06/01/2014
2 rep2 300 06/01/2014
3 rep3 400 06/01/2014
4 rep4 500 06/01/2014
5 rep5 100 06/01/2014
6 rep1 200 02/06/2014
7 rep2 300 02/06/2014
8 rep3 900 02/06/2014
9 rep4 700 02/06/2014
10 rep5 600 02/06/2014
我想要这样的结果:
rep 01/06/2014 02/06/2014
rep1 200 200
rep2 300 300
rep3 400 900
rep4 500 700
rep5 100 600
非常感谢!
最佳答案
您似乎想要每个代表的最新行。这是一种通常表现良好的方法:
select t.*
from table t
where not exists (select 1
from table t2
where t2.repid = t.repid and
t2.id > t.id
);
这将问题转化为:“获取表 t
中的行,其中没有其他行具有相同的 repid
和更大的 id
。”这与获取最后一个逻辑相同,只是稍微复杂一些以帮助数据库知道要做什么。
出于性能原因,t(repid, id)
上的索引很有帮助。
关于Mysql单列结果转多列结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24325395/