0

样本数据:

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

任何帮助...

提前致谢。

4

2 回答 2

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

于 2012-06-29T13:40:15.143 回答
0

纯 T-SQL 本身不支持递归查询,但是您可以使用 SQL Server 公用表表达式(SQL-Server 独有的功能)。

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

于 2012-06-29T15:28:50.960 回答