--WO2405090020
;WITH #TABLE0 AS (
	SELECT t1e.FLOT,t1e.FLOT_TEXT,t1e.FMATERIALID
		,SUM(t1e.FAMOUNT) FAMOUNT,t1e.FMOENTRYID
	FROM T_PRD_PICKMTRLDATA t1e
	GROUP BY t1e.FLOT,t1e.FLOT_TEXT,t1e.FMATERIALID,t1e.FMOENTRYID
),#TABLE1 AS (
	SELECT t0.FBILLNO,t0.FBILLTYPE,t0e.FSEQ,t0e.FMATERIALID AS TopMaterialId
		,t1e.FLOT,t1e.FLOT_TEXT,t1e.FAMOUNT,t1e.FMATERIALID
		,ROW_NUMBER() OVER (PARTITION BY t0e.FID,t0e.FENTRYID ORDER BY t1e.FLOT,t1e.FMATERIALID) RN
		,CONVERT(varchar(1000),t1e.FMATERIALID) AS 'aPATH'
		,1 lv
	FROM T_PRD_MO t0
		INNER JOIN T_PRD_MOENTRY t0e on t0.FID = t0e.FID
		CROSS APPLY ( 
			SELECT t1e.FLOT,t1e.FLOT_TEXT,t1e.FMATERIALID
				,SUM(t1e.FAMOUNT) FAMOUNT,t1e.FMOENTRYID
			FROM T_PRD_PICKMTRLDATA t1e 
			WHERE t1e.FMOENTRYID = t0e.FENTRYID
			GROUP BY t1e.FLOT,t1e.FLOT_TEXT,t1e.FMATERIALID,t1e.FMOENTRYID
		) t1e --on t1e.FMOENTRYID = t0e.FENTRYID
	WHERE t0.FBILLNO = 'RO2405090020'
	UNION ALL
	SELECT t0.FBILLNO,t0.FBILLTYPE,t0e.FSEQ,tt.TopMaterialId--,t0e.FMATERIALID
		,t1e.FLOT,t1e.FLOT_TEXT,t1e.FAMOUNT
		,t1e.FMATERIALID
		,ROW_NUMBER() OVER (PARTITION BY t0e.FID,t0e.FENTRYID ORDER BY t1e.FLOT,t1e.FMATERIALID) RN
		,CONVERT(varchar(1000),CONCAT(tt.aPATH,'.',t1e.FMATERIALID)) AS 'aPATH'
		,tt.lv + 1 lv
	FROM #TABLE1 tt 
		INNER JOIN T_PRD_MO t0 on tt.FLOT_TEXT = t0.FBILLNO
		INNER JOIN T_PRD_MOENTRY t0e on t0.FID = t0e.FID
		INNER JOIN #TABLE0 t1e on t0e.FENTRYID = t1e.FMOENTRYID
)

SELECT * FROM #TABLE1 ORDER BY aPATH
--SELECT * FROM T_PRD_PICKMTRLDATA