【问题标题】:How to multiply two columns and add a new column to the database?如何将两列相乘并向数据库添加新列?
【发布时间】:2022-01-19 08:38:45
【问题描述】:

哪个客户 ID 购买了最多的产品? (提示:通过乘以 product_quantity 和 price_per_item 字段来获得销售额)

SELECT 
    customerid,
    product_quantity * price_per_item as "sales",
    SUM(sales)
FROM questions
GROUP BY customerid

This is how the database looks like

添加销售列后,我无法执行求和运算并收到以下错误:

SELECT customerid, product_quantity * price_per_item as "sales", SUM(sales) FROM questions GROUP BY customerid LIMIT 0, 1000
错误代码:1054。“字段列表”中的“销售”列未知

Desired output

【问题讨论】:

    标签: mysql sql group-by


    【解决方案1】:

    您看到的确切错误是由于产品表达式没有直接出现在聚合函数中。你应该直接取这个产品的总和。使用以下LIMIT 查询可能没问题:

    SELECT customerid
    FROM questions
    GROUP BY customerid
    ORDER BY SUM(product_quantity * price_per_item) DESC
    LIMIT 1;
    

    如果可能有多个客户与最高销售额相关联,则使用:

    SELECT customerid
    FROM questions
    GROUP BY customerid
    HAVING SUM(product_quantity * price_per_item) = (
        SELECT SUM(product_quantity * price_per_item)
        FROM questions
        GROUP BY customerid
        ORDER BY SUM(product_quantity * price_per_item) DESC
        LIMIT 1
    );
    

    【讨论】:

      【解决方案2】:

      您不能在同一个 select 子句中使用在 select 子句中创建的别名,因为表达式没有顺序。这意味着product_quantity * price_per_item as "sales" 不一定在SUM(sales) 之前执行,因此DBMS 会告诉您sales 是未知的。

      无论如何您都不需要别名,因为每个客户只有一个结果行,除了总和之外,您还想显示什么金额?

      SELECT
        customerid,
        SUM(product_quantity * price_per_item) AS sales
      FROM questions
      GROUP BY customerid
      ORDER BY customerid;
      

      不过,这不会让您成为顶级客户。但是您的查询也没有 :-) 这只是解释您的原始查询出了什么问题。

      以下是关于如何在此基础上获得顶级客户的两种选择:

      带有子查询的选项 1(此处为 CTE):

      WITH list AS
      (
        SELECT
          customerid,
          SUM(product_quantity * price_per_item) AS sales
        FROM questions
        GROUP BY customerid
      )
      SELECT *
      FROM list
      WHERE sales = (SELECT MAX(sales) FROM list);
      

      带有解析函数的选项 2:

      SELECT customerid, sales
      FROM
      (
        SELECT
          customerid,
          SUM(product_quantity * price_per_item) AS sales,
          MAX(SUM(product_quantity * price_per_item)) OVER() AS max_sales
        FROM questions
        GROUP BY customerid
      ) with_max
      WHERE sales = max_sales;
      

      【讨论】:

        猜你喜欢
        • 2016-09-27
        • 1970-01-01
        • 2012-12-13
        • 1970-01-01
        • 2013-09-10
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多