SELECT cInvCCode 分类编码,
cInvCName 分类名称,
iInvCGrade 分类层级,
ss.bInvCEnd 是否是末级,
aa.*
FROM InventoryClass ss
LEFT JOIN
(
SELECT *
FROM
(
SELECT cInvCCode AS 一级分类编码,
cInvCName AS 一级分类名称,
iInvCGrade AS 一级分类层级
FROM InventoryClass
WHERE LEN(cInvCCode) = 1
) a
LEFT JOIN
(
SELECT cInvCCode AS 二级分类编码,
cInvCName AS 二级分类名称,
iInvCGrade AS 二级分类层级
FROM InventoryClass
WHERE LEN(cInvCCode) = 2
) b
ON a.一级分类编码 = LEFT(b.二级分类编码, 1)
LEFT JOIN
(
SELECT cInvCCode AS 三级分类编码,
cInvCName AS 三级分类名称,
iInvCGrade AS 三级分类层级
FROM InventoryClass
WHERE LEN(cInvCCode) = 4
) c
ON LEFT(b.二级分类编码, 2) = LEFT(c.三级分类编码, 2)
LEFT JOIN
(
SELECT cInvCCode AS 四级分类编码,
cInvCName AS 四级分类名称,
iInvCGrade AS 四级分类层级
FROM InventoryClass
WHERE LEN(cInvCCode) = 6
) d
ON LEFT(c.三级分类编码, 4) = LEFT(d.四级分类编码, 4)
LEFT JOIN
(
SELECT cInvCCode AS 五级分类编码,
cInvCName AS 五级分类名称,
iInvCGrade AS 五级分类层级
FROM InventoryClass
WHERE LEN(cInvCCode) = 8
) e
ON LEFT(d.四级分类编码, 6) = LEFT(e.五级分类编码, 6)
) aa
ON (
ss.cInvCCode = aa.一级分类编码
OR ss.cInvCCode = aa.二级分类编码
OR ss.cInvCCode = aa.三级分类编码
OR ss.cInvCCode = aa.四级分类编码
OR ss.cInvCCode = aa.五级分类编码
)
WHERE ss.bInvCEnd = 1;