版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013719012/article/details/82188683
场景模拟:
数据库账务明细表中只存有公司1月和7月的账务明细,比如前端人员有以下需求:给定公司ID返回公司今年1-12月账务汇总,如当月没有数据用0代替,并按月份大小排序。
选定一张行数量大于12的表:
SELECT
CASE WHEN length(mon) = 1 THEN concat(LEFT (CURRENT_DATE, 5),'0',mon)
ELSE
concat(LEFT(CURRENT_DATE, 5), mon)
END months
FROM( SELECT @m :=@m + 1 mon FROM share_sys_area,(SELECT @m := 0) a ) aa LIMIT 12
可以得到一下结果:
使用这种方法进行左连接查询,就可以拿到想要结果:
<select id="getTypeSumByMonth" resultType="map">
select
tt.months as mon,
sum(IFNULL(b.YJ_YY_YJ_COUNT,0)) AS yyyCount,
sum(IFNULL(b.YJ_YY_YJ_DEBT,0)) / 10000 AS yyyDebt,
sum(IFNULL(b.YJ_YY_WJ_COUNT,0)) AS yynCount,
sum(IFNULL(b.YJ_YY_WJ_DEBT,0)) / 10000 AS yynDebt,
sum(IFNULL(b.YJ_WY_COUNT,0)) AS ynCount,
sum(IFNULL(b.YJ_WY_DEBT,0)) / 10000 AS ynDebt,
sum(IFNULL(b.STOP_SLOW_COUNT,0)) AS ssCount,
sum(IFNULL(b.STOP_SLOW_DEBT,0)) / 10000 AS ssDebt
from
(SELECT
CASE WHEN length(mon) = 1 THEN concat(LEFT (CURRENT_DATE, 5),'0',mon)
ELSE
concat(LEFT(CURRENT_DATE, 5), mon)
END months
FROM( SELECT @m :=@m + 1 mon FROM share_sys_area,(SELECT @m := 0) a ) aa LIMIT 12) tt
LEFT JOIN share_acc_project_pro b on tt.months = DATE_FORMAT(b.REPORT_TIME,'%Y-%m')
<if test="_parameter != null and _parameter !=''">
AND b.ENT_ID = #{_parameter}
</if>
GROUP BY tt.months
</select>
其他思路
RIGHT JOIN (SELECT '01' as time2 from DUAL UNION ALL
SELECT '02' as time2 from DUAL UNION ALL
SELECT '03' as time2 from DUAL UNION ALL
SELECT '04' as time2 from DUAL UNION ALL
SELECT '05' as time2 from DUAL UNION ALL
SELECT '06' as time2 from DUAL UNION ALL
SELECT '07' as time2 from DUAL UNION ALL
SELECT '08' as time2 from DUAL UNION ALL
SELECT '09' as time2 from DUAL UNION ALL
SELECT '10' as time2 from DUAL UNION ALL
SELECT '11' as time2 from DUAL UNION ALL
SELECT '12' as time2 from DUAL )