请建议如何进行sql查询以便从该表中获取
ID|Number|Type|----------------1 |AA1 |IN |2 |AA2 |OUT |3 |AA3 |IN |4 |AA4 |OUT |into this resultID| IN | OUT |-------------------1 | AA1 | AA2 |2 | AA3 | AA4 |Thanks
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
vhmi4jdf1#
您可以使用会话变量模拟类似行号的功能。我们在两个派生表中分别得到所有的输入和输出,并做一个 LEFT JOIN 在他们身上,得到想要的输出。这甚至适用于 IN 以及 OUT 不是连续的。它还将处理有争议的案件 IN 没有 OUT .如果有一个 OUT 没有 IN .尝试以下查询:
LEFT JOIN
IN
OUT
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
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
`your_table`
WHERE
Type = 'IN'
ORDER BY id ASC) AS t1
@row_no_2:=@row_no_2 + 1 AS row_no, Number
Type = 'OUT'
ORDER BY id ASC) AS t2 ON t2.row_no = t1.row_no
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
SET @row_number = 0;
SET @row_number2 = 0;
out_table.OUTs AS outs, in_table.Ins as INs FROM
(@row_number2:=@row_number2 + 1) AS num2, Number as OUTs FROM your_table WHERE your_table.Type = 'OUT') as out_table ,
(@row_number:=@row_number + 1) AS num1, Number as Ins FROM your_table WHERE your_table.Type = 'IN') as in_table
WHERE num2 = num1
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_TypeFROM table1 a Left join table1 b on a.ID = b.IDGroup by a.ID
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
3条答案
按热度按时间vhmi4jdf1#
您可以使用会话变量模拟类似行号的功能。我们在两个派生表中分别得到所有的输入和输出,并做一个
LEFT JOIN
在他们身上,得到想要的输出。这甚至适用于
IN
以及OUT
不是连续的。它还将处理有争议的案件IN
没有OUT
.如果有一个
OUT
没有IN
.尝试以下查询:
u3r8eeie2#
这将使用隐式连接。
它将使用mysql会话变量。作为参考,你可以阅读http://www.mysqltutorial.org/mysql-variables/ 用于会话变量。
pinkon5k3#
回答我自己。。。