简体   繁体   English

使用带汇总字段的Order by和Group By函数对SQL查询结果进行排序时遇到麻烦

[英]Having troubles sorting SQL query results with Order by and Group By functions with Aggregated fields

I am encountering some issues with the results of the following query. 我的以下查询结果遇到了一些问题。

My intention is to display the results of the total payments received by the hosts, sorted in descending order based on the aggregated column (aliased as 'Total Amount Received ($)' 我的意图是显示主机收到的总付款的结果,并根据汇总列以降序排列(别名为“已收到的总金额($)”)

Select   H.host_name AS 'Host Name', 
         H.location AS 'District', 
         AVG(F.host_feedback_rating) AS 'Average Rating',
         SUM(P.payment_amount) AS 'Total Amount Received ($)'

FROM booking B, host H, payments P, feedback F 
WHERE H.host_id = P.host_id
AND F.booking_code = B.booking_code
AND F.host_id = H.host_id
AND P.payment_date  between '2018/01/01' and '2018/12/31'

GROUP BY 1,2
ORDER BY 'Total Amount Received ($)' DESC;

Current Results: 当前结果:

Host Name   District    Average Rating  Total Amount Received ($)
John         Detroit              5                275
Leeroy       Chicago              5                50
Rinoa        Texas                5                225
Sally        California           4                45

I've tried adjusting the GROUP BY clauses, but somehow the Total Amount Received ($) does not get sorted correctly... Could you please guide me on this? 我试过调整GROUP BY子句,但是总收款($)不能正确排序...您能对此进行指导吗?

Thank you very much! 非常感谢你!

'Total Amount Received ($)' is surrounded by single quotes ( ' ), and is thus a constant string literal. 'Total Amount Received ($)'用单引号( ' )括起来,因此是常量字符串文字。 While sorting according to it isn't technically wrong (as you could see - you got no error), it's meaningless, as all the rows would have the same value of the constant. 虽然按照其排序在技术上没有错(如您所见-您没有错误),但它毫无意义,因为所有行的常量值都相同。

The easiest approach, IMHO, would be to sort according to the column's index instead of its alias: 最简单的方法,恕我直言,将根据列的索引而不是其别名进行排序:

ORDER BY 4 DESC

try with backtick like 尝试像这样的反引号

...ORDER BY `Total Amount Received ($)` DESC

OR 要么

...Order By 4 DESC

or 要么

...SUM(P.payment_amount) DESC

Thanks :) 谢谢 :)

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

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