我需要你的帮助。我有一个名为Test_Result的表,其中包含2列,如下所示。
ID Source_ID
10 1
20 2
30 2
40 3
50 3
60 3
70 4
我正在尝试获得如下输出,但无法获得逻辑。
ID Parent_ID Source_ID
10 Null 1
20 Null 2
30 20 2
40 Null 3
50 40 3
60 50 3
70 Null 4
请帮助我解决这个问题。我也附上了问题。
此致 ABHI
答案 0 :(得分:0)
这些解决方案(ROW_NUMBER / LAG)适用于MySQL 8.0+或MariaDB 10.2
您可以使用ROW_NUMBER()
并加入上一行:
CREATE TABLE tab(ID INT ,Source_ID INT);
INSERT INTO tab(id, Source_id)
SELECT 10, 1
UNION ALL SELECT 20 , 2
UNION ALL SELECT 30, 2
UNION ALL SELECT 40 , 3
UNION ALL SELECT 50 , 3
UNION ALL SELECT 60 , 3
UNION ALL SELECT 70 , 4;
WITH cte AS (
SELECT *, ROW_NUMBER() OVER(ORDER BY id) AS rn
FROM tab
)
SELECT c1.ID,
CASE WHEN c1.Source_ID = c2.Source_ID THEN c2.Id END AS Parent_Id,
c1.Source_ID
FROM cte c1
LEFT JOIN cte c2
ON c1.rn = c2.rn+1;
<强> Rextester Demo 强>
修改强>
使用LAG()
窗口函数:
SELECT c1.ID,
CASE
WHEN c1.Source_ID = LAG(Source_ID) OVER w THEN LAG(ID) OVER w
END AS Parent_Id,
c1.Source_ID
FROM tab c1
WINDOW w AS (ORDER BY ID)
ORDER BY id;
<强> DBFiddle 强>
<强> EDIT2:强>
使用变量模拟LAG
:
SET @lag_Source_id='';
SET @lag_Id = '';
SELECT ID,
CASE WHEN Source_Id = lag_Source_ID THEN lag_ID END AS Parent_ID
,Source_ID
FROM (
SELECT ID
, Source_ID
, @lag_Source_id AS lag_Source_id
, @lag_Source_id:= Source_ID AS curr_Source_ID
, @lag_Id AS lag_ID
, @lag_Id := ID AS curr_ID
FROM tab
ORDER BY id
) AS sub
<强> RextesterDemo2 强>
答案 1 :(得分:0)
如果您使用的是mysql数据库,只需执行此操作,
SELECT ID, (ID + Source_ID) AS Parent_ID, Source_ID FROM tableName LIMIT 10;