SQL Server SQL How to select data like hierarchy

hfwmuf9z  于 2023-06-21  发布在  其他
关注(0)|答案(1)|浏览(153)

I have data like this but I need to show data if user = 'L001' then show only data of row 1,3,4 and if user = 'L002' then show only data of row 2 & 5, how to create a select query? (with no declare variable)

9vw9lbht

9vw9lbht1#

Not sure what you mean by with no declare variable but, in my opinion, you can use recursive CTE to create a hierarchy. Everything depends on the complexity of your data because your example is too short and you can use simple union for select what you need. Anyway, this is just one of many examples how to organaze it.

with rec as(
            select e.*,[USER] as Hierarchy from Employee e 
            where [USER] like 'L%'
            union all
            select e.*, ee.[USER] as Hierarchy from Employee e
            inner join rec ee on ee.SUB = e.MAIN
)
select MAIN,SUB,[USER] from rec where Hierarchy = 'L001'

相关问题