[英]get first value of a field based on the max of another field while other max fields are also being used
[英]SQL… Get Value from Field based on Max value of Another Field
今天有一个完整的SQL思维失误,无法解决。 ColdFusion和MS Access
我正在寻找ColdFusion中的查询查询。
原始查询:
<cfquery name="myQuery" datasource="xxx">
SELECT Name, ID, tblLoc.Directions, tblLoc.LocationOrder
FROM myTable
WHERE .....
ORDER BY tblLoc.LocationOrder
</cfquery>
我想从此查询中创建另一个查询,在该查询中我找到LocationOrder最大的Directions。
因此,如果myQuery返回:
Name ID Directions LocationOrder
AA 10 AAAAAA 1
BB 11 BBBBBB 2
My QoQ would return:
Directions
BBBBBB
但是我尝试过的看似简单的SQL的每次迭代都失败了。 我一定半睡着了。
<cfquery name="latestDirections" dbtype="query">
SELECT Directions
FROM myQuery
WHERE LocationOrder=(select max(LocationOrder) from myQuery)
</cfquery>
<cfquery name="latestDirections" dbtype="query">
SELECT Directions, MAX(LocationOrder) as maxLocationOrder
FROM get_sel_locations
</cfquery>
不...不会做。
...第二个,“列get_sel_locations.Directions在SELECT列表子句中无效,因为它不包含在聚合函数中,并且没有GROUP BY子句”
错误非常明显。 您缺少GROUP BY子句。 当使用像MAX聚集(),你必须GROUP任何非聚集列的结果。 在这种情况下:路线
SELECT Directions, MAX(LocationOrder) as maxLocationOrder
FROM get_sel_locations
GROUP BY Directions
更新但是,如果只想为所有内容提供最大值,那么Yisroel的查询可能就是您想要的。
更新如评论中所述,QoQ 不是数据库查询。 它们仅支持文档http://livedocs.adobe.com/coldfusion/8/using_recordsets_3.html中列出的功能/语法。
SELECT Name, ID, tblLoc.Directions, tblLoc.LocationOrder
FROM myTable
WHERE .....
ORDER BY tblLoc.LocationOrder DESC LIMIT 1;
应该做你。 您在最大LocationOrder上的路线会通过排序和限制来处理。
另一种可能性,如果我正确理解了这个问题:
SELECT x FROM table_name在哪里y =(SELECT MAX(y)FROM table_name)
如果从myQuery中删除ORDER BY子句会发生什么? 另外,说出查询失败的方式。 您得到什么结果?
鉴于您遇到的错误,您可以尝试以下操作:
-- remove the parentheses
WHERE LocationOrder=select max(LocationOrder) from myQuery
要么
-- use IN instead of equals even though your subquery returns a single scalar value and '=' should be fine.
WHERE LocationOrder IN (select max(LocationOrder) from myQuery)
您可以先进行QoQ以获取最大位置
<cfquery name="maxDirections" dbtype="query">
SELECT max(LocationOrder) as maxLocation
FROM myQuery
</cfquery>
<cfquery name="latestDirections" dbtype="query">
SELECT Directions
FROM myQuery
WHERE LocationOrder = '#maxDirections.maxLocation#'
</cfquery>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.