当前位置:网站首页>MySQL queries the quantity of each month and the year-on-year and month on month data of each month

MySQL queries the quantity of each month and the year-on-year and month on month data of each month

2022-06-13 00:36:00 Flying husky

explain : a_query A table is an empty table

#  Query the monthly number of cases reported this year ,  And the year-on-year and month on month data of cases reported every month 
SELECT
	monthData.months AS ' month ',
	monthData.thisMonth AS ' Number of months ',
	IFNULL( CONVERT( ( (monthData.thisMonth - monthData.lastYearThisMonth) / monthData.lastYearThisMonth *100), DECIMAL(10,2) ), 0) AS ' Year on year ', 
	IFNULL( CONVERT( ( (monthData.thisMonth - monthData.lastMonth) / monthData.lastMonth *100), DECIMAL(10,2) ), 0) AS ' Chain ratio '
FROM(	
	SELECT 
		monthTable.months AS months,
		(
			SELECT 
			   COUNT(id) AS tCount
			FROM
			    case_report
			WHERE
			    is_delete = 0 AND DATE_FORMAT(case_report_time, '%Y-%m') = monthTable.months AND case_area_code LIKE('150201%')
		) AS thisMonth,
		(
			SELECT 
			   COUNT(id) AS tCount
			FROM
			    case_report
			WHERE
			    is_delete = 0 AND PERIOD_DIFF(DATE_FORMAT(STR_TO_DATE(CONCAT(monthTable.months,'-01'),"%Y-%m-%d"), '%Y%m' ), DATE_FORMAT(case_report_time, '%Y-%m' )) = 1
			    AND case_area_code LIKE('150201%')
		) AS lastMonth,
		(
			SELECT 
			   COUNT(id) AS tCount
			FROM
			    case_report
			WHERE
			    DATE_FORMAT(case_report_time, '%Y%m') = DATE_FORMAT(DATE_SUB(STR_TO_DATE(CONCAT(monthTable.months,'-01'),"%Y-%m-%d") ,INTERVAL 1 YEAR), '%Y%m')
			    AND case_area_code LIKE('150201%')
		) AS lastYearThisMonth,
		(
			SELECT 
			   COUNT(id) AS tCount
			FROM
			    case_report
			WHERE
			    case_area_code LIKE('150201%')
		) AS totalData
	FROM (SELECT 
		CONCAT('2022-', LPAD(id, 2, '0')) AS months	
	FROM
		a_query
	ORDER BY 
		id	 
	LIMIT 12
	) monthTable
) monthData


原网站

版权声明
本文为[Flying husky]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280600041991.html