如何在此 SQL 查询中使用 WHERE 子句?
我有两个表 - 客户和订单。客户仅包含 ID 和姓名。订单包含订单 ID、客户 ID 和订单金额。我的目标是对每个客户的订单进行求和,即使是没有任何订单的客户(因此,结果集中为 0)。
问题 实际上,我只需要显示每个客户 ID 的总数 << 的条目。 500。我有一个 WHERE 子句用于此目的,但出现错误。
SELECT * FROM orders;
SELECT * FROM customer;
SELECT
c.customer_id, c.customer_name, ISNULL(sum(o.order_total),0) as grand_total
FROM
customer c
LEFT JOIN
orders o
ON
c.customer_id = o.customer_id
--WHERE
--grand_total < 500
GROUP BY
c.customer_id, c.customer_name
ORDER BY
grand_total
我能够通过 LEFT JOIN 来完成此操作,并将客户表放在“左侧”,吸引每一位顾客,并在他们没有订单时显示 0。我将每个订单(按客户)的总和别名为 grand_total。 当我在 ORDER_BY 中使用 grand_total 时,会识别别名,并且 grand_total 列按预期排序。但是,当我在 WHERE 语句中引用 grand_total 别名时(即 WHERE grand_total < 500),我收到错误 无效的列名 'grand_total'
我很困惑为什么 grand_total 在 ORDER_BY 中被识别但不是哪里。除此之外,我正在尝试找到 WHERE 子句的正确语法,以仅包含 grand_total < 的行。 500。
I have two tables - Customers and Orders. Customers just contains an ID and the name. Orders contains an Order ID, a Customer ID, and the amount of the Order. My goal is to sum the orders for each customer,even for customers who didn't have any orders (so, a 0 in the result set).
Problem I actually need to show only the entries for which the total for each customer id < 500. I have a WHERE clause for this, but I get an error.
SELECT * FROM orders;
SELECT * FROM customer;
SELECT
c.customer_id, c.customer_name, ISNULL(sum(o.order_total),0) as grand_total
FROM
customer c
LEFT JOIN
orders o
ON
c.customer_id = o.customer_id
--WHERE
--grand_total < 500
GROUP BY
c.customer_id, c.customer_name
ORDER BY
grand_total
I was able to do this with a LEFT JOIN,and have the Customers table on the "left", to get every customer, and to show a 0 when they had no orders. I aliased the sums of each order (by customer) as grand_total.
When I use grand_total in and ORDER_BY, the alias is recognized, and the grand_total column sorts as expected. But when I reference the grand_total alias in my WHERE statement (i.e. WHERE grand_total < 500), I get the error Invalid column name 'grand_total'
I'm confused as to why grand_total is recognized in the ORDER_BY but not the WHERE. Aside from that, I'm trying to find the right syntax for a WHERE clause to include only the rows for which grand_total < 500.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
具有
用于过滤组的,而不是 :由于您没有指定您正在使用的数据库,因此我将innull isnnull insnull colesce并使用了实际表达式使其完全便携。
还可以通过列数数字按组和顺序,而不是重复表达式,以使查询更容易在眼睛上。
Use
HAVING
for filtering groups, notWHERE
:Since you didn't specify which database you're using, I changed ISNULL to COALESCE and used the actual expression in HAVING, which makes it totally portable.
Also made use of column numbers in GROUP BY and ORDER BY rather than repeating expressions to make the query easier on the eyes.