【问题标题】:sum of values from an array with duplicates具有重复项的数组中的值的总和
【发布时间】:2014-05-14 11:49:31
【问题描述】:

尝试从查询中添加值的总和,但不确定如何让它添加所有值,目前它只是从列表中查找唯一值,但应该添加所有值。

例如 项目 11 的价格是 1 英镑 第 35 件商品的价格是 2 英镑

我正在尝试将 11 和 35 以及 35 的值相加,即(1 英镑+2 英镑+2 英镑)得到 5 英镑的值

我使用的查询显然不符合要求,因为它返回 3 英镑,所以它只是添加附加到唯一项目的唯一值

SELECT sum(price) FROM prices where item_id IN(11,35,35)

非常感谢任何帮助

【问题讨论】:

  • 您的请求失败的原因是因为 IN 是一个集合,而不是一个元组,并且重复的元素是相同的。

标签: php mysql sum


【解决方案1】:

您需要在表上强制进行笛卡尔连接,您可以这样做:

select
    sum(yt.price) as TotalPrice
from
    yourTable yt
        join (
            select
                11 as ID
            from dual
            union all
            select
                35 as ID
            from dual
            union all
            select
                35 as ID
            from dual
        ) sel
            on yt.ID=sel.ID

您创建一个子查询,其中包含您想要的 ID 的多条记录,并将其连接到您想要从中提取数据的实际表中。

您可以做的另一件事是拉回单个商品的价格并将其分类到一个数组/对象中,您可以在其中进行数学运算以更详细的方式获取价格。

您可以使用数组非常简单地做的另一件事(或者您存储要计算价格的 ID)是在外部查询中执行可变数量的联合 - 确实类似于上面,但看起来会很不一样:

select
    sum(sel.price)
from
    (
        select price from yourTable where ID=11
        union all
        select price from yourTable where ID=35
        union all
        select price from yourTable where ID=35
    ) sel

几乎相同,但取决于您拉入查询的其余列,可能更适合。

【讨论】:

    【解决方案2】:

    您需要使用join 执行此操作。 where 子句不会增加行数。所以:

    select sum(price)
    from (select 11 as item union all select 35 union all select 35
         ) i join
         prices p
         on i.item = p.item;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2021-12-06
      相关资源
      最近更新 更多