SQL逐级连接数据

时间:2015-04-12 05:12:14

标签: sql sql-server

我有这样的表

level|value
1    |ABC
1    |XYZ
1    |QWER
2    |1234
2    |7360
3    |zxcv
3    |0001

如何将第1级的每个值加入以下所有级别?像:

ABC-1234-zxcv
ABC-1234-0001
ABC-7360-zxcv

...

2 个答案:

答案 0 :(得分:2)

如果你总是有3个级别,你可以这样做:

select
  d1.value + '-' + d2.value + '-' +  d3.value
from
  data d1 
  cross join data d2
  cross join data d3
where
  d1.level = 1 and
  d2.level = 2 and
  d3.level = 3
order by
  1

如果级别数没有修复,那么你可能不得不使用递归CTE

答案 1 :(得分:2)

级别的数量不固定:

Declare @select varchar(max) = 'SELECT ',
        @from varchar(max) = 'FROM ',
        @where varchar(max) = 'WHERE ',
        @query varchar(max)= '';

SELECT  @select = @select + 't' + cast([level] as varchar(max)) + '.[value]+''-''+',
        @from = @from + 'yourTable t' + cast([level] as varchar(max)) + ',',
        @where = @where + 't' + cast([level] as varchar(max)) + '.[level] = ' + cast([level] as varchar(max)) + ' AND '
FROM yourTable 
GROUP BY [level]

Set @query  = SUBSTRING(@select, 1, len(@select) - 5) + ' ' + 
        SUBSTRING(@from, 1, len(@from) - 1) + ' ' +
        SUBSTRING(@where, 1, len(@where) - 4) + ' ORDER BY 1'

EXEC(@query)