我在数据库中创建了6个月的数据,该数据库的列名为productiondate。我已经为这个生产日期专栏提供了6个月的日期。现在我需要从这个单一的生产日期列中检索每月数据的数据。
我需要以以下方式显示
一月,二月,三月,。。。。。。。。dec在单独的列
您没有提供当前表结构或现有查询的任何详细信息,但听起来您正试图将数据从行透视到列。
MySQL没有pivot函数,因此您需要使用带有CASE
表达式的聚合函数来复制它。您的代码将类似于此:
select otherColumns,
max(case when month(productiondate)=1 then value end) Jan,
max(case when month(productiondate)=2 then value end) Feb,
max(case when month(productiondate)=3 then value end) Mar,
max(case when month(productiondate)=4 then value end) Apr,
max(case when month(productiondate)=5 then value end) May,
max(case when month(productiondate)=6 then value end) Jun,
....
from yourtable
group by otherColumns
然后将otherColumns
替换为希望包含在最终结果中的任何其他列。然后这些列将被包括在CCD_ 3中。此外,您还可以将value
替换为每月要显示的列的名称。
您需要每月使用GROUP BY
并生成月度报告。根据您的需求,您可能还需要使用SUM
、COUNT
、AVG
等聚合函数。
您可以使用MonthName
函数从日期获取月份名称例如
mysql> SELECT MONTHNAME('1998-02-05');
-> 'February'
因此您的查询可能如下所示:
SELECT MONTHNAME(productiondate) as mon, SUM(XYZ), COUNT(*)
FROM Your_Table_Name
GROUP BY mon