需要将行合并为两列

lmvvr0a8  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(307)

请建议如何进行sql查询以便从该表中获取

ID|Number|Type|
----------------
1 |AA1   |IN  |
2 |AA2   |OUT |
3 |AA3   |IN  |
4 |AA4   |OUT |

into this result

ID|  IN  |  OUT |
-------------------
1 | AA1  |  AA2 |
2 | AA3  |  AA4 |

Thanks
vhmi4jdf

vhmi4jdf1#

您可以使用会话变量模拟类似行号的功能。我们在两个派生表中分别得到所有的输入和输出,并做一个 LEFT JOIN 在他们身上,得到想要的输出。
这甚至适用于 IN 以及 OUT 不是连续的。它还将处理有争议的案件 IN 没有 OUT .
如果有一个 OUT 没有 IN .
尝试以下查询:

SET @row_no_1 = 0;
SET @row_no_2 = 0;

SELECT 
    t1.row_no AS ID, t1.Number AS `IN`, t2.Number AS `OUT`
FROM
    (SELECT 
        @row_no_1:=@row_no_1 + 1 AS row_no, Number
    FROM
        `your_table`
    WHERE
        Type = 'IN'
    ORDER BY id ASC) AS t1
        LEFT JOIN
    (SELECT 
        @row_no_2:=@row_no_2 + 1 AS row_no, Number
    FROM
        `your_table`
    WHERE
        Type = 'OUT'
    ORDER BY id ASC) AS t2 ON t2.row_no = t1.row_no
u3r8eeie

u3r8eeie2#

这将使用隐式连接。
它将使用mysql会话变量。作为参考,你可以阅读http://www.mysqltutorial.org/mysql-variables/ 用于会话变量。

SET @row_number = 0;
SET @row_number2 = 0;
SELECT
    out_table.OUTs AS outs, in_table.Ins as INs  FROM
  (SELECT
          (@row_number2:=@row_number2 + 1) AS num2,  Number as OUTs FROM your_table WHERE  your_table.Type = 'OUT')   as out_table ,
       (SELECT
          (@row_number:=@row_number + 1) AS num1,  Number as Ins FROM your_table WHERE  your_table.Type = 'IN')   as in_table
  WHERE num2 = num1
pinkon5k

pinkon5k3#

回答我自己。。。

SELECT a.ID
  MAX(CASE WHEN a.type = "IN" THEN a.Number ELSE "" END) AS IN_Type,
  MAX(CASE WHEN b.type = "IN" THEN b.Number ELSE "" END) AS Out_Type
FROM table1 a Left join table1 b on a.ID = b.ID
Group by a.ID

相关问题