Sql server 查询中每个字段的位置值
在我提出关于(分层数据的反向查询)的问题之前 我得到了90%的答案Sql server 查询中每个字段的位置值,sql-server,Sql Server,在我提出关于(分层数据的反向查询)的问题之前 我得到了90%的答案 select i.ID, l.lev1 as Name, NULL as Parent from IDTable i join LevelTable l on i.Name = l.lev1 union select i.ID, l.lev2 as Name, (select j.ID from IDTable j where j.Name = l.lev1) from IDTable i join LevelTab
select i.ID, l.lev1 as Name, NULL as Parent
from IDTable i
join LevelTable l on i.Name = l.lev1
union
select i.ID, l.lev2 as Name, (select j.ID from IDTable j where j.Name = l.lev1)
from IDTable i
join LevelTable l on i.Name = l.lev2
union
select i.ID, l.lev3 as Name, (select j.ID from IDTable j where j.Name = l.lev2)
from IDTable i
join LevelTable l on i.Name = l.lev3
现在为了完全得到我的答案,我还有一个问题
我如何在我的查询中获得每个字段的位置。例如,管、LCD、等离子电视的父项现在我需要位置字段值,根据字母顺序给出每个位置的值(0、1、2、3…)
category_id | name | parent |position
+-------------+----------------------+--------+-------
| 1 | ELECTRONICS | NULL |0
| 2 | TELEVISIONS | 1 |0
| 3 | TUBE | 2 |3
| 4 | LCD | 2 |1
| 5 | PLASMA | 2 |2
您应该能够将row_number()函数与分区一起使用
select *, row_number() over (partition by parent order by name) as position from (
select i.ID, l.lev1 as Name, NULL as Parent
from IDTable i
join LevelTable l on i.Name = l.lev1
union
select i.ID, l.lev2 as Name, (select j.ID from IDTable j where j.Name = l.lev1)
from IDTable i
join LevelTable l on i.Name = l.lev2
union
select i.ID, l.lev3 as Name, (select j.ID from IDTable j where j.Name = l.lev2)
from IDTable i
join LevelTable l on i.Name = l.lev3
) as q