2015-10-13 44 views
3

MySQL的樞軸在同一個表中具有動態內容MySQL的樞軸在同一個表

創建表的代碼

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; 

我具有表結構如下

+----+------------+---------+--------+ 
| 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 | 
+----+------------+---------+--------+ 

我想有報告格式

+---------+------------+------------+ 
| product | 2015-10-12 | 2015-10-13 | 
+---------+------------+------------+ 
| BOX  |   74 |   36 | 
| SHOE |   35 |   80 | 
| PEN  |   38 |   70 | 
| WATCH |   36 |   73 | 
+---------+------------+------------+ 

我試過到目前爲止

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 
+0

是日期參數,或者你會讓他們從表 –

+0

@BerndBuffen將從表 – vickisys

+0

得到所以它可以很多領域,爲每個日期1? –

回答

1

不幸MySQL沒有實現錶轉軸。因此,有解決辦法以建設動態查詢,這裏是我的例子:

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; 

請注意,如果你有很多您的表的日期也可能會很慢

+0

它的工作完美無瑕,是否有可能優先使用jstl和jsp – vickisys

+0

不幸的是,我從來沒有使用過jstl和jsp,所以我不能回答你的問題。順便說一句你錯誤的答案是正確的:) –

0

請試試這個: 刪除的話查看查詢

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;