对一组链值进行分组

时间:2013-03-11 06:19:15

标签: sql-server sql-server-2008

我在SQL Server 2008中有以下表格

DECLARE @UnitConvert table 
(
  ID int identity(1,1),
  ConvertUnitOne nvarchar(50),
  ConvertUnitTwo nvarchar(50)
) 


INSERT INTO @UnitConvert
SELECT 100,500
UNION ALL SELECT 200,100
UNION ALL SELECT 500,300
UNION ALL SELECT 2000,1000
UNION ALL SELECT 3000,9000
UNION ALL SELECT 2000,700
UNION ALL SELECT 820,3000

SELECT * FROM @UnitConvert

UnitConvertOne中的值等效于UnitConvertTwo 所以它有一个价值链链接

所以我想显示像

这样的结果
Group         unit

1             100

              200

              300

              500

2             700

              1000

              2000

3             820

              3000

              9000

组值将根据可以创建的组数自动增量 单位值可以从小值到大值排序

1 个答案:

答案 0 :(得分:0)

感谢sqlservercentral.com的Eugene Elutin

DECLARE @UnitConvert table 
(
  ID int identity(1,1),
  ConvertUnitOne nvarchar(50),
  ConvertUnitTwo nvarchar(50)
) 

INSERT INTO @UnitConvert
SELECT 100,500
UNION ALL SELECT 200,100
UNION ALL SELECT 500,300
UNION ALL SELECT 2000,1000
UNION ALL SELECT 3000,9000
UNION ALL SELECT 2000,700
UNION ALL SELECT 820,3000

;WITH cteUP AS
(
 SELECT  ConvertUnitTwo AS childUP, ConvertUnitOne AS unitUP, 0 AS Lvl
 FROM @UnitConvert 
 UNION ALL 
 SELECT cte.childUP, u.ConvertUnitOne AS unitUP, Lvl = Lvl + 1 
 FROM @UnitConvert u
 INNER  JOIN cteUP cte ON cte.unitUP = u.ConvertUnitTwo
)
--select * from cteUP
SELECT   c.ConvertUnit
        ,DENSE_RANK() OVER (ORDER BY ISNULL(cm.unitUP, c.ConvertUnit)) AS GrpNO
FROM   (SELECT ConvertUnitOne AS ConvertUnit FROM @UnitConvert 
        UNION 
        SELECT ConvertUnitTwo AS ConvertUnit FROM @UnitConvert) c
OUTER APPLY (SELECT  TOP 1 unitUP FROM cteUP m WHERE
             m.childUP = c.ConvertUnit ORDER BY Lvl DESC) cm