在SQL Server中展平父子关系

时间:2012-06-29 13:15:48

标签: sql-server

示例数据:

我可以使用此查询来平衡父子关系......

任何帮助......

提前致谢。

2 个答案:

答案 0 :(得分:1)

尝试以下方法:

select
COALESCE(mg4.Id,   mg3.Id,   mg2.Id,   mg1.Id,   em.Id)   AS cat1ID,
COALESCE(mg4.Name, mg3.Name, mg2.Name, mg1.Name, em.Name) AS cat1Name,

CASE
  WHEN mg4.Id IS NOT NULL THEN mg3.Id
  WHEN mg3.Id IS NOT NULL THEN mg2.Id
  WHEN mg2.Id IS NOT NULL THEN mg1.Id
  WHEN mg1.Id IS NOT NULL THEN em.Id
END AS cat3ID,
CASE
  WHEN mg4.Id IS NOT NULL THEN mg3.Name
  WHEN mg3.Id IS NOT NULL THEN mg2.Name
  WHEN mg2.Id IS NOT NULL THEN mg1.Name
  WHEN mg1.Id IS NOT NULL THEN em.Name
END AS cat3Name,

CASE
  WHEN mg4.Id IS NOT NULL THEN mg2.Id
  WHEN mg3.Id IS NOT NULL THEN mg1.Id
  WHEN mg2.Id IS NOT NULL THEN em.Id
END AS cat3ID,
CASE
  WHEN mg4.Id IS NOT NULL THEN mg2.Name
  WHEN mg3.Id IS NOT NULL THEN mg1.Name
  WHEN mg2.Id IS NOT NULL THEN em.Name
END AS cat3Name,

CASE
  WHEN mg4.Id IS NOT NULL THEN mg1.Id
  WHEN mg3.Id IS NOT NULL THEN em.Id
END AS cat4ID,
CASE
  WHEN mg4.Id IS NOT NULL THEN mg1.Name
  WHEN mg3.Id IS NOT NULL THEN em.Name
END AS cat4Name,

CASE WHEN mg4.Id IS NOT NULL THEN em.Id   END AS cat5ID,
CASE WHEN mg4.Id IS NOT NULL THEN em.Name END AS cat5Name,

em.Id AS chosenCatId,

CASE WHEN  em.id > 0 THEN 1 ELSE 0 END 
+ CASE WHEN  mg1.id > 0 THEN 1 ELSE 0 END 
+ CASE WHEN  mg2.id > 0 THEN 1 ELSE 0 END 
+ CASE WHEN  mg3.id > 0 THEN 1 ELSE 0 END
+ CASE WHEN  mg4.id > 0 THEN 1 ELSE 0 END AS chosenLevel

from tempCategory em 

left join tempCategory mg1  
on mg1.Id = em.parentCategory

left join tempCategory mg2  
on mg2.Id = mg1.parentCategory

left join tempCategory mg3  
on mg3.Id = mg2.parentCategory

left join tempCategory mg4  
on mg4.Id = mg3.parentCategory

我省略了最后一次加入,因为您的查询未从mg5中提取任何列。

SQL Fiddle的这个查询:http://sqlfiddle.com/#!3/a6f01/5

答案 1 :(得分:0)

Pure T-SQL本身不支持递归查询,但您可以使用SQL Server公用表表达式(仅限SQL服务器)。

这是一个涵盖SQL-Server CTE递归的页面:http://msdn.microsoft.com/en-us/library/ms186243(v=sql.105).aspx