mysql建立数据透视表,MySQL数据透视表

本文介绍如何使用MySQL创建动态内容的表格透视,以展示产品在不同日期的销售数据。作者分享了现有表结构、目标报告格式以及使用GROUP_CONCAT和动态查询实现的解决方案,提醒读者处理大量日期可能带来的性能问题。
摘要由CSDN通过智能技术生成

MySQL pivot in same table with dynamic content

Create Table Code

CREATE TABLE `product_table` (

`id` INT(10) NOT NULL,

`pdate` DATE NULL DEFAULT NULL,

`product` VARCHAR(50) NULL DEFAULT NULL,

`counts` VARCHAR(50) NULL DEFAULT NULL,

PRIMARY KEY (`id`)

)

COLLATE='utf8_general_ci'

ENGINE=InnoDB;

I have table structure as below

+----+------------+---------+--------+

| id | pdate | product | counts |

+----+------------+---------+--------+

| 1 | 2015-10-12 | BOX | 74 |

| 2 | 2015-10-12 | SHOE | 35 |

| 3 | 2015-10-12 | PEN | 38 |

| 4 | 2015-10-12 | WATCH | 36 |

| 5 | 2015-10-13 | BOX | 36 |

| 6 | 2015-10-13 | SHOE | 80 |

| 7 | 2015-10-13 | PEN | 70 |

| 8 | 2015-10-13 | WATCH | 73 |

+----+------------+---------+--------+

I would like to have report as this format

+---------+------------+------------+

| product | 2015-10-12 | 2015-10-13 |

+---------+------------+------------+

| BOX | 74 | 36 |

| SHOE | 35 | 80 |

| PEN | 38 | 70 |

| WATCH | 36 | 73 |

+---------+------------+------------+

what i tried so far

select

d.p product,

(select date(p.pdate) from product_table p where date(p.pdate)=d.dt and p.product = d.p ) date,

(select p.counts from product_table p where date(p.pdate)=d.dt and p.product = d.p ) cnt

from

(select pt.product p,date(pt.pdate) dt from product_table pt group by pt.product,date(pt.pdate) ) as d

group by product

解决方案

Unfortunately MySQL does not have implemented table pivoting. So there is workaround with building a dynamic query, here is my example:

SELECT

GROUP_CONCAT(DISTINCT(

CONCAT(

'MAX(

IF(pt.pdate = \'', pdate, '\', pt.counts, null)

) AS \'' , pdate, '\''

)

)

) INTO @dates FROM product_table;

SET @query = CONCAT('SELECT product, ', @dates, ' FROM product_table pt GROUP BY product');

PREPARE stmt FROM @query;

EXECUTE stmt;

Please note that if you have a lot of dates in your table it may be very slow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值