如何将多行合并为一行?

时间:2012-10-10 14:45:34

标签: mysql

  

可能重复:
  Combine Multiple child rows into one row 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的count和“inventory_id = 2”的“Resource 2”提供别名“Resource 1”

需要输出:

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

2 个答案:

答案 0 :(得分: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 Fiddle DEMO

这应该给你:

RESOURCE 1  RESOURCE 2  RESOURCE_ID
10             20                1
30             40                2

答案 1 :(得分: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 Demo

<击>

但是如果您的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 Demo