分组统计SQL(mysql)

<select id="orderProductStatistics" resultMap="ProductStatisticsVOMap">
SELECT
ls.*,IFNULL(sr.out_count,0) AS out_count
FROM
(
SELECT
od.product_id,pri.`product_type`,
GROUP_CONCAT(DISTINCT pri.`name`) AS product_name,
IFNULL(SUM(od.`product_num`),0) AS dj_count
FROM order_detail od
LEFT JOIN order_info oi ON od.`order_id`=oi.`id`-- 订单信息
LEFT JOIN product_info pri ON od.`product_id`=pri.`id`-- 产品信息
<where>
(oi.`is_cancel` ='' OR oi.`is_cancel` IS NULL OR oi.`is_cancel`='0')
<if test="startDate != null">
AND (DATE_FORMAT(oi.`create_time`,'%Y-%m-%d') &gt;= #{startDate})
</if>
<if test="endDate != null">
AND (DATE_FORMAT(oi.`create_time`,'%Y-%m-%d') &lt;= #{endDate})
</if>
</where>
GROUP BY od.product_id
) AS ls
LEFT JOIN
(
SELECT
psr.`product_id`,SUM(psr.`product_count`) AS out_count
FROM product_stock_record psr
<where>
psr.`stock_type`='0'
<if test="startDate != null">
AND (DATE_FORMAT(psr.`create_time`,'%Y-%m-%d') &gt;= #{startDate})
</if>
<if test="endDate != null">
AND (DATE_FORMAT(psr.`create_time`,'%Y-%m-%d') &lt;= #{endDate})
</if>
</where>
GROUP BY psr.`product_id`
) sr ON sr.product_id = ls.product_id
</select>

猜你喜欢

转载自www.cnblogs.com/sung1024/p/11700309.html