1. 程式人生 > >sql 某欄位關聯今年1-12月月份值查詢

sql 某欄位關聯今年1-12月月份值查詢

場景模擬:

資料庫賬務明細表中只存有公司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 :[email protected] + 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 :[email protected] + 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 )