DECLARE @tblProducts TABLE(Id INT IDENTITY, ProductName varchar(50),Quality varchar(50), ProductWeight int)
INSERT INTO @tblProducts SELECT 'Demir-1','ST-1',10
INSERT INTO @tblProducts SELECT 'Demir-2','ST-2',7
INSERT INTO @tblProducts SELECT 'Demir-3','ST-1',20
INSERT INTO @tblProducts SELECT 'Demir-2','ST-3',8
INSERT INTO @tblProducts SELECT 'Demir-1','ST-3',6
INSERT INTO @tblProducts SELECT 'Demir-4','ST-2',10
INSERT INTO @tblProducts SELECT 'Demir-2','ST-2' ,12
INSERT INTO @tblProducts SELECT 'Demir-1','ST-1',15
INSERT INTO @tblProducts SELECT 'Demir-1','ST-3',10
INSERT INTO @tblProducts SELECT 'Demir-3','ST-3' ,5
INSERT INTO @tblProducts SELECT 'Demir-2' ,'ST-2 ',5
;WITH Cte (Id,ProductQuality,ProductIds,ProductNames,ProductQualities,ProductTotalWeight,ProductWeights,ProductName1,ProductName2) AS
(
SELECT Id
,Quality
, ',' + CAST(Id AS VARCHAR(MAX))
,',' + CAST(ProductName AS VARCHAR(MAX))
,',' + CAST(Quality AS VARCHAR(MAX))
,ProductWeight
, ',' + CAST(ProductWeight AS VARCHAR(MAX))
,ProductName
,CAST(ProductName AS VARCHAR(MAX))
FROM @tblProducts
UNION ALL
SELECT p.Id
, p.Quality
,c.ProductIds + ',' + CAST(p.Id AS VARCHAR(MAX))
,c.ProductNames + ',' + CAST(p.ProductName AS VARCHAR(MAX))
,c.ProductQualities + ',' + CAST(p.Quality AS VARCHAR(MAX))
,c.ProductTotalWeight + p.ProductWeight
,c.ProductWeights + ',' + CAST(p.ProductWeight AS VARCHAR(MAX))
,p.ProductName
,c.ProductName2
FROM @tblProducts AS p JOIN Cte c ON p.Id < c.Id
WHERE p.ProductName = c.ProductName2
)
SELECT
ProductIds = STUFF(ProductIds,1,1,'')
,ProductNames = STUFF(ProductNames,1,1,'')
,ProductQualities = STUFF(ProductQualities,1,1,'')
,ProductTotalWeight
,ProductWeights = STUFF(ProductWeights,1,1,'')
FROM CTE
WHERE ProductTotalWeight BETWEEN 20 AND 25
结果
ProductIds ProductNames ProductQualities ProductTotalWeight ProductWeights
3 Demir-3 ST-1 20 20
11,7,2 Demir-2,Demir-2,Demir-2 ST-2 ,ST-2,ST-2 24 5,12,7
11,7,4 Demir-2,Demir-2,Demir-2 ST-2 ,ST-2,ST-3 25 5,12,8
11,4,2 Demir-2,Demir-2,Demir-2 ST-2 ,ST-3,ST-2 20 5,8,7
10,3 Demir-3,Demir-3 ST-3,ST-1 25 5,20
9,1 Demir-1,Demir-1 ST-3,ST-1 20 10,10
9,8 Demir-1,Demir-1 ST-3,ST-1 25 10,15
8,1 Demir-1,Demir-1 ST-1,ST-1 25 15,10
8,5 Demir-1,Demir-1 ST-1,ST-3 21 15,6
7,4 Demir-2,Demir-2 ST-2,ST-3 20 12,8