简体   繁体   English

MySQL枢轴在同一个表中

[英]MySQL pivot in same table

MySQL pivot in same table with dynamic content MySQL在与动态内容相同的表中进行透视

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. 不幸的是,MySQL没有实现表格旋转。 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 请注意,如果您的表中有很多日期,可能会非常慢

please try this: remove the remark to see the Query 请尝试此操作:删除备注以查看查询

 SELECT DISTINCT
  CONCAT(   'SELECT p.product  ',
  GROUP_CONCAT( 
  CONCAT(   ',SUM( IF(pdate = \'', pdate,'\', p.count,0)) as \'', pdate,'\'') SEPARATOR '\n'),
  ' FROM product_table p GROUP BY p.product;') INTO @sql FROM product_table p;

-- SELECT @sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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