Home  >  Article  >  Database  >  Sample code sharing for mysql column switching and year and month grouping

Sample code sharing for mysql column switching and year and month grouping

黄舟
黄舟Original
2017-03-25 13:27:19968browse

The following editor will bring you an example of mysqlcolumn transfer and year and monthgrouping. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

As shown below:

SELECT count(DISTINCT(a.rect_id)) zcount, a.job_dept, 

DATE_FORMAT(submit_date, '%Y-%m') zsubmit_date 

FROM 

表名 a 

WHERE 

a.statu = 3 

AND a.rstatu = 2 

AND a.job_dept IN ('19', '20', '21') 

GROUP BY 

a.job_dept, 

DATE_FORMAT(submit_date, '%Y-%m')

The key is DATE_FORMAT(submit_date, '%Y-%m ')Group and sort the time, year and month

SELECT      
zsubmit_date,      
MAX(CASE WHEN job_dept = '19' THEN zcount ELSE 0 END ) 19zcount,      
MAX(CASE WHEN job_dept = '20' THEN zcount ELSE 0 END ) 20zcount,      
MAX(CASE WHEN job_dept = '21' THEN zcount ELSE 0 END ) 21zcount  

FROM    
(     
SELECT       
count(DISTINCT(a.rect_id)) zcount, a.job_dept,        
DATE_FORMAT(submit_date, '%Y-%m') zsubmit_date     
FROM       
表名 a     
WHERE       
a.statu = 3       
AND a.rstatu = 2       
AND a.job_dept IN ('19', '20', '21')     
GROUP BY     
a.job_dept,     
DATE_FORMAT(submit_date, '%Y-%m')    
) q  GROUP BY    
zsubmit_date

The above is the detailed content of Sample code sharing for mysql column switching and year and month grouping. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn