sql query of a field associated with the month value from January to December of this year

Keywords: Database

Scene simulation:

The database account details only contain the company's account details in January and July. For example, the front-end personnel have the following needs: given the company ID, return the company's account summary in January December this year. If there is no data in the current month, use 0 instead, and sort by month size.

Select a table with more than 12 rows:

        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

The following results can be obtained:

Using this method to query the left connection, you can get the desired result:

<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>

Other ideas

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 )

Posted by PunkGo on Sat, 04 Jan 2020 00:28:47 -0800