统计过去12个月数据

  SELECT
    t1.yf AS 'month',
    count( t2.task_name ) AS total
    FROM
    (
    SELECT
    DATE_FORMAT(( CURDATE()), '%Y-%m' ) AS 'yf' UNION
    SELECT
    DATE_FORMAT(( CURDATE() - INTERVAL 1 MONTH ), '%Y-%m' ) AS 'yf' UNION
    SELECT
    DATE_FORMAT(( CURDATE() - INTERVAL 2 MONTH ), '%Y-%m' ) AS 'yf' UNION
    SELECT
    DATE_FORMAT(( CURDATE() - INTERVAL 3 MONTH ), '%Y-%m' ) AS 'yf' UNION
    SELECT
    DATE_FORMAT(( CURDATE() - INTERVAL 4 MONTH ), '%Y-%m' ) AS 'yf' UNION
    SELECT
    DATE_FORMAT(( CURDATE() - INTERVAL 5 MONTH ), '%Y-%m' ) AS 'yf' UNION
    SELECT
    DATE_FORMAT(( CURDATE() - INTERVAL 6 MONTH ), '%Y-%m' ) AS 'yf' UNION
    SELECT
    DATE_FORMAT(( CURDATE() - INTERVAL 7 MONTH ), '%Y-%m' ) AS 'yf' UNION
    SELECT
    DATE_FORMAT(( CURDATE() - INTERVAL 8 MONTH ), '%Y-%m' ) AS 'yf' UNION
    SELECT
    DATE_FORMAT(( CURDATE() - INTERVAL 9 MONTH ), '%Y-%m' ) AS 'yf' UNION
    SELECT
    DATE_FORMAT(( CURDATE() - INTERVAL 10 MONTH ), '%Y-%m' ) AS 'yf' UNION
    SELECT
    DATE_FORMAT(( CURDATE() - INTERVAL 11 MONTH ), '%Y-%m' ) AS 'yf'
    ) t1
    LEFT JOIN
    (
    SELECT t.* FROM gs_task t LEFT JOIN gs_task_user gsu on t.orderSn = gsu.orderSn
    where gsu.user_id=#{userId} and t.current_stage = #{currentStage}
    )t2
    on DATE_FORMAT( t2.start_time, '%Y-%m' )= t1.yf
    GROUP BY t1.yf
    order by t1.yf ASC

你可能感兴趣的:(sql)