如何从多列表中识别叶节点?

14ifxucb  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(312)

我有一个表,有多个类别/子类别列

我想确定作为叶节点的行。叶节点可以在任何级别上,例如,对于dresses,第11个节点是叶节点,因为它没有子节点。如何在mssql中实现这一点?

bfnvny8b

bfnvny8b1#

你可以用 not exists . sql server现在有了一个方便的功能 concat_ws() 这在这里很有用:

with t as (
      select t.*,
             concat_ws('->', group_1, group_2, group_3, group_4) as groups
      from <table> t
     )
select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.groups like concat(t.groups, '->%')
                 );

这很简单,没有 concat_ws() 也:

with t as (
      select t.*,
             concat('->' + group_1,
                    '->' + group_1,
                    '->' + group_3,
                    '->' + group_4
                   ) as groups
      from <table> t
     )

注意:这两者都使用 concat() 以及 + 因为他们能处理 NULL 价值观不同。 concat() 忽略 NULL 价值观,但是 + 返回一个 NULL 如果有任何参数 NULL .

相关问题