根据产品ID获取salesQty的总和

时间:2014-04-26 09:19:38

标签: mysql

我有以下查询:

select pt_product_name,
  (select 
     sum(sal_qty)
   from sales_tb as sal
   where pt.pt_productid=sal.sal_pt_productid
   and sal.sal_updated_time>curdate()
  ) as salQty
from product_tb as pt

它为每个产品返回sal_qty的sum,但我希望sum基于不同的产品。 你能指点我正确的方向吗,我错过了什么?感谢。

2 个答案:

答案 0 :(得分:0)

GROUP BY pt.pt_productid添加到您的select语句,以将sum()应用于产品组。

另请考虑使用JOIN而不是嵌套选择。

<强>更新

select pt_product_name, 
  (select sum(sal_qty) from sales_tb as sal
    where pt.pt_productid=sal.sal_pt_productid
    and sal.sal_updated_time>curdate()
  ) as salQty
  from product_tb as pt
  group by pt.pt_productid; 

使用 JOIN

select pt_product_name, sum(sal_qty) as salQty
  from product_tb as pt
  left outer join sales_tb sal on (pt.pt_productid = sal.sal_pt_productid 
      and sal.sal_updated_time>curdate())
  group by pt.pt_productid

这是一个填充了示例值的示例表结构,以及查询工作正常的演示:

    DROP TABLE IF EXISTS `temp_db`.`product_tb`;
    CREATE TABLE  `temp_db`.`product_tb` (
        pt_productid int(10) not null auto_increment,
        pt_product_name varchar(20) not null,
        primary key (`pt_productid`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
    DROP TABLE IF EXISTS `temp_db`.`sales_tb`;
    CREATE TABLE  `temp_db`.`sales_tb` (
        sal_saleid int(10) not null auto_increment,
        sal_pt_productid int(10) not null references product_tb.pt_productid,
        sal_qty int(10) default 0,
        sal_updated_time timestamp not null default current_timestamp,
        primary key (`sal_saleid`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

将样本数据添加到表中:

    insert into product_tb(pt_product_name) values 
        ('prod1'), ('prod2'), ('prod3'), ('prod4');
    insert into sales_tb(sal_pt_productid, sal_qty) values 
        (1, 40), (1, 40), (1, 10), (1, 20),
        (2, 4), (2, 4), (2, 4), (2, 4), 
        (3, 1), (3, 1), (3, 1),
        (4, 5), (4, 5);

select语句的结果(都返回相同的结果集):

# pt_product_name, salQty
prod1   110
prod2   16
prod3   3
prod4   10

注意,如果数量仅在今天或之后销售 * ,则只会对其进行求和! sal_update_time > curdate();

如果产品没有curdate()或更高版本的任何销售,它甚至不会出现在列表中。这并不意味着选择错误,这意味着您没有正确指定目标是什么。

答案 1 :(得分:0)

select 
    pt.pt_product_name,
    sum(sal.sal_qty) as salQty
from
    product_tb as pt
        left join
    sales_tb as sal on pt.pt_productid = sal.sal_pt_productid
where
    sal.sal_updated_time > curdate()
group by pt.pt_productid

此查询将所有产品与各自的销售相结合。然后,它将同一产品的所有记录组合在一起。然后根据当前日期过滤记录。这些组中的每一组将包含单个产品的每次销售的一个记录。最后,在选择中,我们总结每个组的所有销售数量。

相关问题