SUM一个子查询?

时间:2011-09-27 00:21:12

标签: mysql

查看具有类似标题的问题,但没有一个完全涵盖我的问题。我的查询看起来像这样。

   SELECT
      bus_products.id
      , bus_products.prod_name
      , (
         SELECT SUM(bus_warehouse_entries.quantity) * bus_products.weight
         FROM bus_warehouse_entries
         WHERE bus_warehouse_entries.org_product_code = bus_products.prod_code
         AND bus_warehouse_entries.type = 0
         AND bus_warehouse_entries.request_date >= 'some_date_here'
      ) AS reg_yr
   FROM
      bus_products
   WHERE 1'some_search_params'
   GROUP BY bus_products.prod_name
   ORDER BY 'some_sort'

当我按产品名称分组时,子查询通过匹配产品代码进行选择。多个产品代码可能具有相同的产品名称。如果有多个具有相同名称的代码,则上述查询仅获取由于分组而产生的第一个代码的数量。

我想在子查询周围添加一个SUM(),以便获得具有该特定产品名称的所有产品代码的总和,但这会在子查询SELECT的开头导致语法错误。关于如何以另一种方式实现这一目标的任何建议?

为简化起见,表格看起来像这样

bus_products
id | prod_code | prod_name | weight

bus_warehouse_entries
org_product_code | quantity | type | request_date

4 个答案:

答案 0 :(得分:7)

SELECT x.prod_name
     , SUM(x.total)
  FROM ( SELECT bp.prod_name
              , ( SELECT SUM( wh.quantity ) * bp.weight 
                    FROM bus_warehouse_entries wh
                   WHERE bp.prod_code = wh.org_product_code ) AS total
       FROM bus_products bp ) x
 GROUP BY x.prod_name

您可以在from中的select中添加更多子查询,并在外部查询中对它们求和。

答案 1 :(得分:1)

试试这个:

select b.id, b.prod_name, sum(bwe.quantity)*b.weight as reg_yr 
from bus_products b inner join 
bus_warehouse_entries bwe on bwe.org_product_code=b.prod_code 
where bwe.type=0 and bwe.request_date>='some date' 
group by b.id,b.prod_name, b.weight

更新:那怎么样?

SELECT
      bus_products.id
      , bus_products.prod_name
      , f.part_total  
   FROM
      bus_products bus_products 
      inner join (
         SELECT SUM(bus_warehouse_entries.quantity) * bus_products.weight as part_total
         ,bus_products.prod_code as p_code
         FROM bus_warehouse_entries bus_warehouse_entries join  bus_products 
         on bus_products.prod_code=bus_warehouse_entries.org_product_code
         WHERE bus_warehouse_entries.type = 0
         AND bus_warehouse_entries.request_date >= 'some_date'
         group by bus_products.prod_code,bus_products.weight
      )  f on f.p_code=bus_products.prod_code

答案 2 :(得分:0)

尝试将整个内容包装在另一个查询中。

SELECT id, prod_name, sum(reg_yr)
FROM (your query)
GROUP BY id, prod_name

答案 3 :(得分:0)

为了帮助支持我的回答,以及您在问题中的评论,听起来您想要产品名称而不是ID ...例如:您可以拥有20种产品,这些产品都是电视产品名称实际上听起来像类别与特定产品名称。每个“产品名称”都会有更具体的“什么”。因此,您需要加入ID的唯一理由是获得与仓库库存相关的适当权重。那就是说,我会尝试这个......

select 
      bp.prod_name,
      sum( wh.quantity * bp.weight ) as TotalWeight
   from
      bus_warehouse_entries wh
         join bus_products bp
            on wh.org_product_code = bp.prod_code
   where
          wh.type = 0
      and wh.request_date >= 'some_date'
      and (any other criteria)
   group by
      bp.prod_name
   order by
      bp.prod_name (or whatever else)