Mysql多次求和

时间:2018-04-04 05:41:35

标签: mysql sql

我在下表结构中创建了三个表和列表。

1)th_sales_inventory:

id    
user_id    
invoice_date   
increment  
invoice_num    
client_address 
total  
shiping    
roundoff   
company_id 
status 
created_date   
updated_date   
updated_by  
created_by 

表数据: enter image description here

2)th_product

id 
cat_id
name  
description   
purchase_price
selling_price 
image 
company_id
status
created_date  
updated_date  
created_by
updated_by

表数据:

enter image description here 3)th_sales_inventory_detail

id 
product_id
sales_inventory_id
selling_price 
qty   
amount

表数据:

enter image description here

我创建了销售发票和存储在相应表格中的值。我希望根据发票日期获得每个产品销售的总数量,总金额。

我正在使用以下MySQL查询,但我没有正确得到结果。

SELECT p.id as pid,p.name, SUM(sid.qty) as sqty, SUM(total) AS sum,sid.qty, SUM(sid.qty * p.purchase_price) as pu_sum
FROM th_sales_inventory as si
    LEFT JOIN th_sales_inventory_detail as sid ON sid.sales_inventory_id = si.id
    LEFT JOIN th_product as p ON sid.product_id = p.id
WHERE `invoice_date` LIKE '2018-03-%' AND si.company_id = '1'
GROUP BY sid.product_id 

输出:

pid name        sqty     sum     qty     pu_sum     
1   thaaimann   2.000   80.00   2.000   20.00000
2   tomoto1     15.000  340.00  2.000   150.00000

0 个答案:

没有答案