mysql 将两个统计的结果集合并成一行

进销存管理系统中,要统计商品的剩余、销售、总数(剩余+销售)的数量和金额。为了减少对数据库的操作,使用一条SQL查出结果。

1 剩余数量及金额

 2 销售数量及金额

要求将两行结果集合并成一行结果集

SQL操作如下:

EXPLAIN
select remain_total,remain_total_money,seller_count,seller_count_money,remain_total+seller_count as mileage_total,remain_total_money+seller_count_money as mileage_total_money  from (
SELECT
	IFNULL( sum( remain ), 0 ) remain_total,
	IFNULL( sum( remain * union_price ), 0 ) remain_total_money,
  1  'id'
FROM
	(
	SELECT
		wms_product_detail.* 
	FROM
		`wms_product_detail`,
		wms_product_detail_attribute 
	WHERE
		wms_product_detail.id = wms_product_detail_attribute.detail_id 
		AND wms_product_detail.`status` = 0 
		AND wms_product_detail.del_flag = 0 
	GROUP BY
	wms_product_detail.id 
	) AS product ) as tb1
	left join ( select * from (
	SELECT
		IFNULL( sum( count ), 0 ) seller_count,IFNULL(sum(now_price),0)  seller_count_money,1  'id'
	FROM
		( (
		SELECT
			wms_order.* 
		FROM
			`wms_product_detail`,
			wms_order,
			wms_product_detail_attribute 
		WHERE
			wms_product_detail.id = wms_order.detail_id 
			AND wms_product_detail.id = wms_product_detail_attribute.detail_id 
			AND wms_order.`status` = 0 
			AND wms_order.del_flag = 0 
		GROUP BY
			wms_order.id 
		) AS tmp ) ) as orderTable) as tb2 on tb1.id=tb2.id

猜你喜欢

转载自blog.csdn.net/Lixuanshengchao/article/details/103506449