如何根据值执行层次结构数据

时间:2015-11-14 11:31:48

标签: sql-server tsql sql-server-2012

我在这张表中包含以下数据

 Cat     CatID        Tag
 0         1        LapTop
 1         2         Mac
 1         3         HP
 1         4         Acer
 1         5         Sony
 1         6         DELL
 6         7         Latitude
 6         8         Vostro
 6         9         inspiron
 6         10        xps

根据Cat和CatID的值,我希望得到这个结果 if Cat=0我希望在列中显示值,如果CatID=Cat我希望在另一列中显示值,我想在新表中插入值

 Tag       Libelle    Type
 LapTop     Mac
 LapTop     HP
 LapTop     Acer
 LapTop     Sony
 LapTop     DELL      Latitude
 LapTop     DELL      Vostro
 LapTop     DELL      inspiron
 LapTop     DELL      xps

1 个答案:

答案 0 :(得分:1)

简单INNERLEFT联接操作可以生成所需的结果集:

SELECT t1.Tag, t2.Tag AS Libelle, 
       COALESCE(t3.Tag, '') AS Type
FROM mytable AS t1
INNER JOIN mytable AS t2 ON t1.CatID = t2.Cat
LEFT JOIN mytable AS t3 ON t2.CatID = t3.Cat
WHERE t1.Cat = 0

Demo here