我的查询是这样的:
SELECT Product.local_price*Rate.exchange_rate AS 'US_price' FROM Product
INNER JOIN Rate ON Rate.currency = Product.currency
WHERE Product.type='TV'
HAVING US_price BETWEEN 500 AND 600;
如何计算满足此查询的电视机数量?
表格结构
答案 0 :(得分:2)
将HAVING US_price
替换为AND Product.local_price * Rate.exchange_rate
,然后在COUNT(Product.ID)
子句中执行SELECT
:
SELECT COUNT(Product.ID)
FROM Product
INNER JOIN Rate ON Rate.currency = Product.currency
WHERE Product.type='TV'
AND Product.local_price * Rate.exchange_rate BETWEEN 500 AND 600;
如果您需要汇总数据的标准,则需要使用HAVING
,如下所示:
SELECT p.type, AVG(p.local_price)
FROM Product p
GROUP BY p.type
HAVING AVG(p.local_price) > 50
答案 1 :(得分:1)
此处无需使用HAVING
条款;只有拥有GROUP BY
子句时,它的特殊语义才有意义。因此,我们可以简单地将US_price
子句中的HAVING
替换为生成它的表达式,并将其移动到WHERE
子句中;然后,使用SELECT COUNT(*)
:
SELECT COUNT(*)
FROM Product
JOIN Rate
ON Rate.currency = Product.currency
WHERE Product.type = 'TV'
AND Product.US_price * Rate.exchange_rate BETWEEN 500 AND 600
;
此外,作为一般规则 - 在这种情况下不需要 - 您可以始终(或几乎总是?)将整个查询包装在SELECT COUNT(*) FROM (...) t
中以获取它返回的总行数。