1

我在 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

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

4

1 回答 1

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
于 2013-03-11T13:01:36.970 回答