简体   繁体   中英

display month names as column names in mysql

I want to display year and month names as column names between two dates inside my procedure as below

year    jan      Feb  ......Dec
----    -----   -----       -----
2016    val1       val2     val3
2017    val4       val5    val6

some one help me to do this

You could do something like this if i understand you question correctly to generate the desired resultset. TIMESTAMPDIFF(DAY.... + INTERVAL 1 MONTH) makes it possible to calculate the days within a month. Please note that months have to be right in every TIMESTAMPDIFF(DAY, '2016-01-01', '2016-01-01' + INTERVAL 1 MONTH) AS 'Jan' line and it should work.

Query

SELECT 
   '2016' AS YEAR
 , TIMESTAMPDIFF(DAY, '2016-01-01', '2016-01-01' + INTERVAL 1 MONTH) AS 'Jan'
 , TIMESTAMPDIFF(DAY, '2016-02-01', '2016-02-01' + INTERVAL 1 MONTH) AS 'Feb'
 ...
 , TIMESTAMPDIFF(DAY, '2016-12-01', '2016-12-01' + INTERVAL 1 MONTH) AS 'Dec'

UNION ALL 

SELECT 
   '2017' AS YEAR
 , TIMESTAMPDIFF(DAY, '2017-01-01', '2017-01-01' + INTERVAL 1 MONTH) AS 'Jan'
 , TIMESTAMPDIFF(DAY, '2017-02-01', '2017-02-01' + INTERVAL 1 MONTH) AS 'Feb'
 ...
 , TIMESTAMPDIFF(DAY, '2017-12-01', '2017-12-01' + INTERVAL 1 MONTH) AS 'Dec'

Result

year       Jan     Feb     Dec  
------  ------  ------  --------
2016        31      29        31
2017        31      28        31

Or this query makes it eazier to add a new year and less code duplication.

Query

SELECT 
   years.year
 , TIMESTAMPDIFF(DAY, CONCAT(years.year, '-01-01'), CONCAT(years.year, '-01-01') + INTERVAL 1 MONTH) AS 'Jan'
 , TIMESTAMPDIFF(DAY, CONCAT(years.year, '-02-01'), CONCAT(years.year, '-02-01') + INTERVAL 1 MONTH) AS 'Feb'
 ...
 , TIMESTAMPDIFF(DAY, CONCAT(years.year, '-12-01'), CONCAT(years.year, '-12-01') + INTERVAL 1 MONTH) AS 'Dec'
FROM ( 

  SELECT 
   '2016' AS YEAR

  UNION 
  ALL

  SELECT 
    '2017' AS YEAR
)
 AS years 

Result

year       Jan     Feb     Dec  
------  ------  ------  --------
2016        31      29        31
2017        31      28        31

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM