0

我有一个包含 3 列的表。Location_ID、Product_ID 和数量:

LOCATION_ID |   PRODUCT_ID    |  QTY
--------------------------------
1                   1              1
2                   1              3
1                   3              5
2                   3              2
2                   4              2
1                   4              5

每次将产品带入或带出某个位置时,都会在此表中创建或更新一行。

是否可以根据表中的 Location_ID 数量进行添加列的查询?

我希望结果是这样的:

PRODUCT_ID | 1 | 2 |
--------------------
    1        1   3
    3        5   2
    4        5   2 

并且如果稍后添加更多的 LOCATION_ID,查询中将有一个名为 location id (3) 的新列。

4

1 回答 1

0

您必须为此使用动态 SQL

SET @sql = NULL;

SELECT GROUP_CONCAT(DISTINCT
         CONCAT('SUM(CASE WHEN location_id = ', location_id,
                ' THEN qty END) `', location_id, '`'))
  INTO @sql
  FROM table1;

SET @sql = CONCAT('SELECT product_id, ', @sql, ' 
                     FROM table1 
                    GROUP BY product_id');

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

输出:

| PRODUCT_ID | 1 | 2 |
|------------|---|---|
| 1 | 1 | 3 |
| 3 | 5 | 2 |
| 4 | 5 | 2 |

这是SQLFiddle演示


为了简化客户端的事情,您始终可以将其包装到存储过程中

DELIMITER $$
CREATE PROCEDURE products_by_location()
BEGIN
  SET @sql = NULL;

  SELECT GROUP_CONCAT(DISTINCT
           CONCAT('SUM(CASE WHEN location_id = ', location_id,
                  ' THEN qty END) `', location_id, '`'))
    INTO @sql
    FROM table1;

  SET @sql = CONCAT('SELECT product_id, ', @sql, ' 
                       FROM table1 
                      GROUP BY product_id');

  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;

并使用它

CALL products_by_location();

这是SQLFiddle演示

于 2013-10-13T06:21:44.710 回答