您正在尝试将数据从行转换为列。MySQL 没有数据透视函数,但您可以使用带有 a 的聚合函数CASE
来获取结果:
select product,
sum(case when month(date) = 12 and year(date) = 2012
then qty else 0 end) Dec2012,
sum(case when month(date) = 1 and year(date) = 2013
then qty else 0 end) Jan2013
from yourtable
group by product
请参阅SQL Fiddle with Demo。
这也可以使用子查询来编写,以获取月-年格式的日期:
select product,
sum(case when MonthYear = 'Dec_2012' then qty else 0 end) Dec2012,
sum(case when MonthYear = 'Jan_2013' then qty else 0 end) Jan2013
from
(
select product,
date_format(date, '%b_%Y') MonthYear,
qty
from yourtable
) src
group by product;
请参阅SQL Fiddle with Demo。
然后,如果您想动态生成日期列表或想要返回未知数量的日期,您可以使用准备好的语句来生成动态 SQL:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(case when MonthYear = ''',
MonthYear,
''' then qty else 0 end) AS ',
MonthYear
)
) INTO @sql
FROM
(
select product,
date_format(date, '%b_%Y') MonthYear,
qty
from yourtable
) src;
SET @sql = CONCAT('SELECT product, ', @sql, '
from
(
select product,
date_format(date, ''%b_%Y'') MonthYear,
qty
from yourtable
) src
GROUP BY product');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
请参阅SQL Fiddle with Demo。这三个都会给你结果:
| PRODUCT | DEC_2012 | JAN_2013 |
------------------------------------
| reference1 | 4 | 0 |
| reference2 | 2 | 9 |
| reference3 | 0 | 6 |