gpt4 book ai didi

SQL语句不按升序排列名称

转载 作者:行者123 更新时间:2023-12-04 03:22:08 24 4
gpt4 key购买 nike

我正在做一个 SQL 练习,其中的任务是:“按平均支付的贷款费用降序排列结果,并按名字和姓氏升序排列结果。”不知何故我无法做到按升序排列名称。有人知道怎么解决吗?

SELCT first_name, last_name, ROUND(avg, 2) AS Leihgebuehr
FROM (
SELECT first_name, last_name, avg
FROM (
SELECT customer.first_name, customer.last_name,
AVG(payment.amount) AS avg
FROM payment
INNER JOIN customer ON payment.customer_id =
customer.customer_id
GROUP BY first_name, last_name
)
WHERE avg > 5
ORDER BY avg DESC, first_name ASC, last_name ASC
)

My current output

最佳答案

您的查询大部分是正确的。问题是您首先在 un-rounded AVG 上排序,这可能几乎是唯一的,因此虽然结果看起来排序不正确,但次要排序顺序永远不会出现发挥作用。

To Prove this, add the un-rounded avg into your existing output so you can see the raw values.

改为更改 ORDER BY 子句以对舍入值而不是原始值进行排序:

SELECT first_name, last_name, ROUND(avg, 2) AS Leihgebuehr
FROM (
SELECT first_name, last_name, avg
FROM (
SELECT customer.first_name, customer.last_name,
AVG(payment.amount) AS avg
FROM payment
INNER JOIN customer ON payment.customer_id =
customer.customer_id
GROUP BY first_name, last_name
)
WHERE avg > 5
ORDER BY ROUND(avg, 2) DESC, first_name ASC, last_name ASC
)

也许在计算聚合值时将聚合值四舍五入更简单,实际上我们可以使用HAVING子句对聚合结果应用过滤条件,而不必使用子查询对于如此简单的结果集。

  SELECT 
customer.first_name,
customer.last_name,
ROUND(AVG(payment.amount), 2) AS Leihgebuehr
FROM payment
INNER JOIN customer ON payment.customer_id = customer.customer_id
GROUP BY first_name, last_name
HAVING AVG(payment.amount) > 5
ORDER BY ROUND(AVG(payment.amount), 2) DESC, first_name ASC, last_name ASC

我们其实可以进一步简化这个,在大多数RDBMS中,在ORDER BY子句中使用列表达式的别名是有效的,这样我们就不会不小心把公式表达式弄错了,或者随着表达式的发展,我们可能会忘记更新列定义或 ORDER BY

中的表达式

注意:此别名用法适用于ORDER BY,不适用于WHEREJOIN 或其他子句。

SELECT 
customer.first_name,
customer.last_name,
ROUND(AVG(payment.amount), 2) AS Leihgebuehr
FROM payment
INNER JOIN customer ON payment.customer_id = customer.customer_id
GROUP BY first_name, last_name
HAVING AVG(payment.amount) > 5
ORDER BY Leihgebuehr DESC, first_name ASC, last_name ASC

关于SQL语句不按升序排列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68325841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com