我在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组值将根据可创建的组数自动递增单元值可以从小到大排序
发布于 2013-03-11 21:01:37
感谢来自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) cmhttps://stackoverflow.com/questions/15332329
复制相似问题