我想在我的程序中的两个日期之间显示年份和月份名称作为列名,如下所示
year jan Feb ......Dec
---- ----- ----- -----
2016 val1 val2 val3
2017 val4 val5 val6
有人帮我做这个
答案 0 :(得分:2)
如果我理解你正确地生成所需的结果集,你可以做这样的事情。
TIMESTAMPDIFF(DAY.... + INTERVAL 1 MONTH)
可以计算一个月内的天数。
请注意,每个TIMESTAMPDIFF(DAY, '2016-01-01', '2016-01-01' + INTERVAL 1 MONTH) AS 'Jan'
行必须正好几个月,它应该有效。
<强>查询强>
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'
<强>结果强>
year Jan Feb Dec
------ ------ ------ --------
2016 31 29 31
2017 31 28 31
或者这个查询使得添加新年和更少的代码重复变得更加容易。
<强>查询强>
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
<强>结果强>
year Jan Feb Dec
------ ------ ------ --------
2016 31 29 31
2017 31 28 31