简体   繁体   English

在WHERE语句中使用别名列

[英]Using Alias Column in WHERE Statement

I know that I cannot use an alias column inside of a WHERE clause, so I'm trying to figure out the best way to write my query, but am struggling. 我知道我不能在WHERE子句中使用别名列,因此我试图找出编写查询的最佳方法,但是却很费劲。 I tried "HAVING" to filter it, but then I can't use GROUP BY at the same time, which makes my Subtotal column sum all of the records in the entire DB. 我尝试使用“ HAVING”对其进行过滤,但是随后我无法同时使用GROUP BY,这使我的“小计”列将整个数据库中的所有记录相加。

Here's what I'm trying to do: 这是我想做的事情:

SELECT a.ID, SUM(b.Qty * b.Price) AS Subtotal
FROM tbl_One AS a
LEFT JOIN tbl_Two AS b ON b.TwoID = a.ID
WHERE Subtotal > 100 AND Subtotal < 200
GROUP BY a.ID

Any suggestions on how I could do this differently would be greatly appreciated! 我将以不同的方式提出任何建议,将不胜感激!

You're right, you cannot call out your alias in the WHERE or HAVING clauses, but other than that I'm not sure what you mean; 没错,您无法在WHERE或HAVING子句中调出别名,但除此之外,我不确定您的意思; GROUP BY and HAVING are meant to be used together: GROUP BY和HAVING旨在一起使用:

SELECT a.ID, sum(b.Qty*b.Price) AS Subtotal
FROM tbl_One AS a
LEFT JOIN tbl_Two AS b ON b.TwoID = a.ID
GROUP BY a.ID
HAVING sum(b.Qty*b.Price) > 100 AND sum(b.Qty*b.Price) < 200

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

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