SQL Group By查询-获取聚合函数的相关字段
简化了,但对于这样的表:
id time distance price 1 20 500 8 2 50 500 10 3 90 500 12 4 80 1000 17 5 170 1000 11 6 180 1000 13 7 19 800 12
我想获取距离 500 和 1000 的最快时间的行,即
id time distance price 1 20 500 8 4 80 1000 17
如果我这样做,那么
select min(time) from table
可以很好地查找价格,但我无法获取 id 和价格 - 只能获取所有 ID/价格的最大/最小/平均值/第一个值。
我可以通过多次查找来完成 - 例如
select * from table where distance = 500 and time = 20 select * from table where distance = 1000 and time = 80
,但是有没有一种更好的方法不涉及 1 +(距离数)查询(或至少提供一个结果集,即使在内部它使用该数量的查询)
Simplified, but for a table like:
id time distance price 1 20 500 8 2 50 500 10 3 90 500 12 4 80 1000 17 5 170 1000 11 6 180 1000 13 7 19 800 12
I want to get the rows with the quickest time for the distances 500 and 1000, i.e.
id time distance price 1 20 500 8 4 80 1000 17
If I do
select min(time) from table
that works fine for finding the price, but I can't get the id and price - only the max/min/average/first value of all ids/prices.
I can do it with multiple look ups - e.g.
select * from table where distance = 500 and time = 20 select * from table where distance = 1000 and time = 80
but is there a better way that doesn't involve 1 + (number of distances) queries (or at least provides one resultset, even if internally it uses that number of queries)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您将需要使用内部选择:
You will need to use an inner select:
您需要将 min 内容放入having子句中,因此您的查询将是
select * from table group by distancehaving min(distance);
(未经测试)
或者您可以使用子查询来查找:
select * from table where distance = (select distance from table where min(time)) and time = select min(time) from table)
(也未经测试:))you need to put the min stuff into a having clause, so your query would be
select * from table group by distance having min(distance);
(untested)
or you could use subquerys to find that out:
select * from table where distance = (select distance from table where min(time)) and time = select min(time) from table)
(also untested :))只需按顺序和限制即可。那么您可以在 1 次查询中获得 500 距离的最快速度。
just order by and limit. then you have the fastest for the 500 distance in 1 query.
试试这个——
Try this one -
这个怎么样……正是您正在寻找的东西(已测试)
What about this one ... gies exactly what you are looking for (TESTED)