【问题标题】:How to get a cumulative total within a select如何在选择中获得累计总数
【发布时间】:2019-11-07 08:53:48
【问题描述】:

我尝试从每个订单中获取税金 + TurnoverExTAX 的累计总额。每个订单有 x 个产品。对于 1 个产品,很容易得到结果。但是每个订单有 x 个产品,我不知道如何获得每个订单行的累积总数。

正如您在下面看到的,订单 1901112055 确实有 2 个结果行。税收总额 = 7.28057851 + 3.80950413

我该如何解决这个问题? 良好的结果 = 11.09008264

Orders_id   TAX     TurnoverExTax   
1901112055  7.28057851  34.66942149     
1901112055  3.80950413  18.14049587     

当我执行 GROUP BY orders_id 时,我得到 1 行,但没有字段累积;税 - TurnoverExTax

 Orders_id  TAX     TurnoverExTax   
 1901112055 7.28057851  34.66942149     

这里简化了我尝试过的 SELECT:

    SELECT DISTINCT
    orders.orders_id AS Orders_id,
            (orders_products.final_price) - (orders_products.final_price / ((orders_products.products_tax /100) + 1)) as TAX,
            (orders_products.final_price / ((orders_products.products_tax /100) + 1) ) AS TurnoverExTax
    FROM
            multi_ts24_nl.orders orders
    INNER JOIN
            multi_ts24_nl.orders_products AS orders_products
    ON
            orders_products.orders_id = orders.orders_id
    WHERE
        orders.orders_id = 1901112055

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    只需使用聚合(添加GROUP BYSUM()

    SELECT o.orders_id as Orders_id,
           SUM((p.final_price) -
               (p.final_price /
               ((p.products_tax / 100) + 1))) as Tax,
           SUM((p.final_price /
               ((p.products_tax / 100) + 1))) as TurnoverExTax
      FROM multi_ts24_nl.orders o
      JOIN multi_ts24_nl.orders_products AS p
        ON p.orders_id = o.orders_id
     WHERE o.orders_id = 1901112055
     GROUP BY Orders_id
    

    为简单起见,为表名使用较短的别名

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 2013-05-03
      相关资源
      最近更新 更多