sql server:关于查询组和自动id的问题

pkbketx9  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(336)

我有一个表,有两列,像这样,图片是输入和输出:

说明输入:2栏是两个关系在一起的人。检查:a与b、c、d、h的关系输出:我想合并2列,列组id为auto和列关系
id group auto:我尝试了query:row\u number()over(order by[columna])n
关系:将所有人的关系分组在一起,并将他们分组为一个id组。检查人员a、b、c、d、h实现在一起,组id自动为1
我有个演示https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=f81ff386b07589654ad133a8e4b30472
在我的查询中,首先我把数据转换成一列,然后我数字母,下一步我不知道查询。
我尝试了递归cte,但出现了错误(也许我对递归不太了解)
我想在sql查询中解决这个问题。

htzpubme

htzpubme1#

可以使用递归cte为每个“列”值指定一个数字。首先在两个方向上创建边,然后跟随它们:

with pairs as (
      select columnA, columnB from myTable
      union -- on purpose to remove duplicates
      select columnB, columnA from myTable
     ),
     cte as (
      select distinct columnA, columnA as columnB,
             convert(varchar(max), ',' + columnA + ',') as visited,
             1 as lev
      from pairs
      union all
      select cte.columnA, p.columnB, concat(visited, p.columnA, ','), lev + 1
      from cte join
           pairs p
           on cte.columnB = p.columnA
      where cte.visited not like concat('%,', p.columnB, ',%') and
            lev < 5
     )
select cte.columnA, min(cte.columnB),
       dense_rank() over (order by min(cte.columnB))
from cte
group by cte.columnA;

然后,您可以将其加入以分配组id:

with pairs as (
      select columnA, columnB from myTable
      union -- on purpose to remove duplicates
      select columnB, columnA from myTable
     ),
     cte as (
      select distinct columnA, columnA as columnB,
             convert(varchar(max), ',' + columnA + ',') as visited,
             1 as lev
      from pairs
      union all
      select cte.columnA, p.columnB, concat(visited, p.columnA, ','), lev + 1
      from cte join
           pairs p
           on cte.columnB = p.columnA
      where cte.visited not like concat('%,', p.columnB, ',%') and
            lev < 5
     ),
     groups as (
      select cte.columnA, min(cte.columnB) as min_columnB,
             dense_rank() over (order by min(cte.columnB)) as group_id
      from cte
      group by cte.columnA
     )
select t.*, g.group_id
from mytable t join
     groups g
     on g.columnA = t.columnA;

这是一把小提琴。

相关问题