2014-04-26 53 views
-3

我有以下查詢:得到salesQty基地SUM產品ID

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根據不同的產品。 您能否指點我正確的方向,我錯過了什麼?謝謝。

+1

請使用代碼格式化,並嘗試生成具有預期輸出的數據樣本。 –

回答

0

GROUP BY pt.pt_productid添加到您的選擇聲明中,以便將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); 

選擇語句的結果(都返回相同的結果集):

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

注意,一個量將只相加,如果它今天或晚些時候賣出*sal_update_time > curdate();

如果產品沒有curdate()或更高版本的任何銷售,它甚至不會出現在列表中。這並不意味着選擇錯誤,這意味着你沒有正確指定你的目標是什麼。

+0

請提供任何示例 – jingly

+0

我有三個產品,但它顯示了一個產品和總和(allprdqty) – jingly

+0

請用您的表格結構和當前搜索語句爲您提供一行更新。 – rekaszeru

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 

該查詢將所有產品與其各自的銷售加入。然後將同一產品的所有記錄分組在一起。記錄然後根據當前日期進行過濾。這些組中的每一組都將包含單個產品的每次銷售記錄。最後,在我們選擇的總和中,對於每個組,所有售出的數量。

+0

它給出了像產品名稱和總和(allprdQty)的答案,但我想prdname總和(prdqty) – jingly

+0

總和(...)只適用於每個組(因爲團隊)。每個組包含單個產品的所有銷售。因此,它會爲每個產品返回一行。每行將包含產品名稱以及該產品已售出的次數。 – Stefano

+0

再次我有同樣的問題 – jingly