有一张表···
··ID··type··code··name··parentID··
··1··大类···1···水泥···null···
··2··小类···1··速凝水泥···1····
··3··小类···2··慢凝水泥···1····
··4··品牌···1··feifei····2····
··5··品牌···2···nini····2····
在一张表里面的类别有 大类,小类和品牌···parentID是标示···就是在 大类:水泥 下面有两种小类:速凝水泥和慢凝水泥···而速凝水泥又有两个品牌····parentID指向的是 上级目录的ID·············
求一句代码
找出大类代码为1 小类代码为1 的品牌····
要求 显示 大类code 大类name 小类code 小类name 品牌code 品牌name··
··ID··type··code··name··parentID··
··1··大类···1···水泥···null···
··2··小类···1··速凝水泥···1····
··3··小类···2··慢凝水泥···1····
··4··品牌···1··feifei····2····
··5··品牌···2···nini····2····
在一张表里面的类别有 大类,小类和品牌···parentID是标示···就是在 大类:水泥 下面有两种小类:速凝水泥和慢凝水泥···而速凝水泥又有两个品牌····parentID指向的是 上级目录的ID·············
求一句代码
找出大类代码为1 小类代码为1 的品牌····
要求 显示 大类code 大类name 小类code 小类name 品牌code 品牌name··
select
大类code = max(case when type = '大类' then code end),
大类name = max(case when type = '大类' then code end),
小类code = max(case when type = '小类' then code end),
小类name = max(case when type = '小类' then code end),
品牌code = max(case when type = '品牌' then code end),
品牌name = max(case when type = '品牌' then code end),或者
select
大类code = (case when type = '大类' then code end),
大类name = (case when type = '大类' then name end),
小类code = (case when type = '小类' then code end),
小类name = (case when type = '小类' then name end),
品牌code = (case when type = '品牌' then code end),
品牌name = (case when type = '品牌' then name end)
from Table_1
还有另外一种方法 可以去掉NULL ,较麻烦点
二者 有区别的
select
大类code = max(case when type = '大类' then code end),
大类name = max(case when type = '大类' then code end),
小类code = max(case when type = '小类' then code end),
小类name = max(case when type = '小类' then code end),
品牌code = max(case when type = '品牌' then code end),
品牌name = max(case when type = '品牌' then code end),或者
select
大类code = (case when type = '大类' then code end),
大类name = (case when type = '大类' then name end),
小类code = (case when type = '小类' then code end),
小类name = (case when type = '小类' then name end),
品牌code = (case when type = '品牌' then code end),
品牌name = (case when type = '品牌' then name end)
from Table_1
还有另外一种方法 可以去掉NULL ,较麻烦点
二者 有区别的
select * from b where parentID in (select parentID from a where parentID is null and code=1 and type='大类' ) and code=1 and type='小类'
(
id INT,
style VARCHAR(10),
code INT,
name VARCHAR(50),
pid INT
)
INSERT INTO t1
SELECT 1,'大类',1,'水泥',NULL UNION ALL
SELECT 2,'小类',1,'速凝水泥',1 UNION ALL
SELECT 3,'小类',2,'慢凝水泥',1 UNION ALL
SELECT 4,'品牌',1,'feifei',2 UNION ALL
SELECT 5,'品牌',2,'nini',2
SELECT * FROM t1SELECT a.code AS [大类code],a.NAME AS [大类name],b.code AS [小类code],b.NAME AS [小类name],c.code AS [品牌code],
c.NAME AS [品牌name]
FROM t1 AS a WITH(NOLOCK) INNER JOIN t1 AS b ON b.pid=a.code AND a.pid IS NULL AND b.code=2 INNER JOIN
t1 AS c WITH(NOLOCK) ON c.pid=b.code AND c.style='品牌'-------------------------------
大类code 大类name 小类code 小类name 品牌code 品牌name
1 水泥 2 慢凝水泥 1 feifei
1 水泥 2 慢凝水泥 2 niniPS:建议既然想采用类似BOM结构存储数据,那么type列和code列就不应该这么取值,比如code都是1,但根本分不清到底是大类、小类还是品牌,一般建议采用类似1.1.1这种方式来记录比较好。