4

可能重复:
将多个子行合并为一行 MYSQL

我有下表,

count     | inventory_id | resource_id | id
---------+-----------+----------------------
10        | 1            | 1           | 1
20        | 2            | 1           | 2
30        | 1            | 2           | 3
40        | 2            | 2           | 4

我想合并resource_id 相等的行,并且还想根据inventory_id 为每个计数提供别名。我需要为inventory_id = 1的计数和inventory_id = 2的“资源2”提供别名“资源1”

需要的输出:

Resource 1| Resource 2    |resource_id 
---------+-----------+-----------------
10        | 20            | 1             
30        | 40            | 2             
4

2 回答 2

3
SELECT
  MAX(CASE WHEN inventory_id = 1 THEN `count` END) AS 'Resource 1',
  MAX(CASE WHEN inventory_id = 2 THEN `count` END) AS 'Resource 2',
  resource_id
FROM table 
GROUP BY resource_id

SQL 小提琴演示

这应该给你:

RESOURCE 1  RESOURCE 2  RESOURCE_ID
10             20                1
30             40                2
于 2012-10-10T14:47:47.930 回答
2

尝试

SELECT
  resource_id,
  MAX(CASE WHEN inventory_id = 1 THEN `count` ELSE NULL END) AS 'Resource 1',
  MAX(CASE WHEN inventory_id = 2 THEN `count` ELSE NULL END) AS 'Resource 2'
FROM table1
GROUP BY resource_id

SQLFiddle 演示

但是如果你有未知的值inventory_id不仅仅是(1 and 2),更好地使用PreparedStatement

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN inventory_id = ',
      inventory_id,
      ' THEN `count` ELSE NULL END) AS ''RESOURCE ',
      inventory_id, ''''
    )
  ) INTO @sql
FROM table1;

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

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

SQLFiddle 演示

于 2012-10-10T15:04:05.367 回答