ID PARENT MC 001.001 001 拉丝机 001.001.001 001.001 轴承 001.001.001.001 001.001.001 垫片
我想查询得到 如果我给的ID 为001.001.001.001,并且要示显示二级
希望得到
ID 一级 二级 MC 001.001.001.001 拉丝机 轴承 垫片
如何我给的ID 为001.001.001,并且要示显示二级
希望得到
ID 一级 二级 MC 001.001.001 无 拉丝机 轴承
------解决方案--------------------
[code=SQL][ IF NOT OBJECT_ID('tb') IS NULL DROP TABLE tb create table tb (id varchar(50), parent varchar(50),mc varchar(50)) insert into tb select '001.001','001','拉丝机' insert into tb select '001.001.001','001.001','轴承' insert into tb select '001.001.001.001','001.001.001','垫片'
---根据底层物料查询上层物料(物料用途)
with at as ( select a.parent,a.id ,0 as levl,mc from tb a where a.id='001.001.001.001'--这里是条件 union all select a.parent,a.id,levl - 1 ,a.mc from tb a join at on a.id=at.parent ) select a.id,一级,二级,mc from ( select max(id)id,max(case when levl=-2 then mc else null end )as "一级",max(case when levl=-1 then mc else null end) as "二级" from at )a join tb on a.id=tb.id /* id 一级 二级 mc 001.001.001.001 拉丝机 轴承 垫片