MySQL Pivot View Dynamic

时间:2018-01-15 12:42:11

标签: mysql pivot pivot-table

我有一张像

这样的表格

+-----------------------------------+-------------------------------------------+-------------+
| warehouse                         | item_code                                 | stock_value |
+-----------------------------------+-------------------------------------------+-------------+
| 103-VAN DXB- U56403 NADEEM - DLTL | Alcatel 1054D 1054E BLACK CHARCOAL GREY   | 500         |
+-----------------------------------+-------------------------------------------+-------------+
| 103-VAN DXB- U56403 NADEEM - DLTL | Alcatel 1054D 1054E BLACK+PURE WHITE      | 15000       |
+-----------------------------------+-------------------------------------------+-------------+
| 100-Main Warehouse - Nahda - DLTL | Alcatel 2008D WHITE+METAL SILVER DUAL SIM | 45643       |
+-----------------------------------+-------------------------------------------+-------------+
| 100-Main Warehouse - Nahda - DLTL | Alcatel 2008D-BLACK METAL SILVER DUAL SIM | 4544        |
+-----------------------------------+-------------------------------------------+-------------+

http://www.sqlfiddle.com/#!9/c4fe92/1/0

列仓库名称未修复。那么我如何创建如下的数据透视表

+-------------------------------------------+----------------+--------+----------------+-------------+
| item                                      | Main Warehouse | NADEEM | total quantity | total value |
+-------------------------------------------+----------------+--------+----------------+-------------+
| Alcatel 1054D 1054E BLACK CHARCOAL GREY   | 0              | 1      | 1              | 500         |
+-------------------------------------------+----------------+--------+----------------+-------------+
| Alcatel 1054D 1054E BLACK+PURE WHITE      | 0              | 1      | 1              | 1500        |
+-------------------------------------------+----------------+--------+----------------+-------------+
| Alcatel 2008D WHITE+METAL SILVER DUAL SIM | 1              | 0      | 1              | 45643       |
+-------------------------------------------+----------------+--------+----------------+-------------+
| Alcatel 2008D-BLACK METAL SILVER DUAL SIM | 1              | 0      | 1              | 4544        |
+-------------------------------------------+----------------+--------+----------------+-------------+

1 个答案:

答案 0 :(得分:0)

这是一种方法,假设您要从仓库字段中解析所需信息:

SELECT item_code, 
  IF(LOCATE('Main Warehouse', warehouse), 1, 0) AS `Main Warehouse`, 
  IF(LOCATE('NADEEM', warehouse), 1, 0) AS `NADEEM`, 
  COUNT(item_code) AS total_quantity
FROM some_table
GROUP BY item_code