如果id相同,则多个SQL行合并为单行

时间:2017-07-24 20:27:50

标签: mysql sql

在下表中我需要获得的结果是什么mysql:

表:

+----+-------+--------------
| name| id   |  items | vol
+----+-------+---------------
|  A | 1111  |  4     |  170
|  A | 1111  |  5     |  100
|  B | 2222  |  6     |  200
|  B | 2222  |  7     |  120
+----+-------+-----------------

上表是联合查询的结果

SELECT * FROM imports
union all
SELECT * FROM exports
ORDER BY name;

我想创建一个看起来像这样的临时视图

期望的结果:

+----+---------+---------+-------------------
| name| id     | items |  vol | items1 | vol2
+-----+--------+-------+--------------------
|  A  | 1111   |   4   |  170 |   5    | 100
|  B  | 2222   |   6   |  200 |   7    | 120
+----+---------+---------+-------------------

任何帮助将不胜感激! -Thanks

2 个答案:

答案 0 :(得分:1)

使用PIVOT:

SELECT name,id,
       SUM( CASE WHEN typ = 'imports' THEN items ELSE 0 END) as imports_items,
       SUM( CASE WHEN typ = 'imports' THEN vol   ELSE 0 END) as imports_vol,
       SUM( CASE WHEN typ = 'exports' THEN items ELSE 0 END) as exports_items,
       SUM( CASE WHEN typ = 'exports' THEN vol   ELSE 0 END) as exports_vol
FROM (
   SELECT 'imports' as typ, t.* FROM imports t
   union all
   SELECT 'exports' as typ, t.* FROM exports t
) x
GROUP BY name,id
ORDER BY name;

答案 1 :(得分:0)

这应该会为您提供您正在寻找的表格:

    SELECT 
        a.name, 
        a.id, 
        a.items, 
        a.vol, 
        b.items as items2, 
        b.vol as vol2
    FROM imports a 
        INNER JOIN exports b on b.id = a.id;