总和超过200的MYSQL SELECT行

时间:2018-04-21 04:42:45

标签: mysql sql

如何选择行总和超过200的行?

我尝试了grouping的各种组合,设置AS并使用WHERE子句

目前的尝试如下

SELECT something.CustomerName, something.CustomerAge, cars.Prices, 
       SUM(cars.Price) AS Amount 
FROM cars 
INNER JOIN something ON something.CustomerNo=Cars.CustomerNo 
GROUP BY AMOUNT 
WHERE AMOUNT > '200' 

我找不到关于如何做到这一点的教程

2 个答案:

答案 0 :(得分:1)

根据您当前的尝试where条款应该在group by子句

之前
SELECT something.CustomerName, something.CustomerAge, 
       SUM(cars.Price) AS Amount 
FROM cars 
INNER JOIN something ON something.CustomerNo=Cars.CustomerNo  
GROUP BY something.CustomerName, something.CustomerAge
HAVING SUM(cars.Price) > 200;

但是,您确实需要在Amount上应用过滤器,但是,您无法通过where子句执行此操作,因为您需要应用having子句过滤器而不是比where子句

我今天的建议是使用表格alise,它可以更易读,更容易使用/实施

SELECT s.CustomerName, s.CustomerAge,
       SUM(c.Price) AS Amount 
FROM cars as c -- use of alise to make it more effective or readable
INNER JOIN something as s ON s.CustomerNo = c.CustomerNo  -- and use that alise everywhere entire the query 
GROUP BY s.CustomerName, s.CustomerAge
HAVING SUM(c.Price) > 200;

答案 1 :(得分:0)

您可以使用子查询来计算数学,然后选择所需的值

SELECT * FROM
(
    SELECT (col1 + col2) AS SumOfCols, table.* FROM table
)
WHERE SumOfCols > 200

或者另一种类似的方法是加入临时表

SELECT table.* FROM table
INNER JOIN
(
    SELECT ID, (col1 + col2) AS SumOfCols FROM table
) AS TableSums ON TableSums.ID = table. ID
WHERE TableSums.SumOfCols > 200