【问题标题】:MYSQL SELECT rows where sum is over 200 [duplicate]总和超过200的MYSQL SELECT行[重复]
【发布时间】:2018-10-01 19:23:46
【问题描述】:

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

我尝试了与grouping 的各种组合,设置了一些东西并使用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' 

我找不到有关如何执行此操作的教程

【问题讨论】:

  • 你试过什么??向我们展示您当前的尝试。
  • 我认为 200 是个小数字,没什么大不了的
  • 一行的总和是多少?
  • SELECT something.CustomerName, something.CustomerAge, cars.Prices, SUM(cars.Price) AS Amount FROM cars INNER JOIN something ON something.CustomerNo=Cars.CustomerNo GROUP BY @987654326 @ WHERE AMOUNT > '200' 我试过不使用''符号,没有帮助

标签: mysql sql


【解决方案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;

【讨论】:

    【解决方案2】:

    您可以使用子查询进行数学运算,然后选择您想要的值

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-25
      • 2010-10-30
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      相关资源
      最近更新 更多