我正在重写一个写得不好的应用程序的几页,我试图将此逻辑作为子查询并入主查询中,以便我可以一口气获取所有数据,而不必像当前代码那样连接50K次。
我从
开始DECLARE @combinedString NVARCHAR(MAX),@mds NVARCHAR(MAX)
SELECT
@combinedString = COALESCE(@combinedString + ', ', '') + serial,
@mds = MDS
FROM
(aircraftserials
LEFT JOIN
serialnums ON serialnums.ID = aircraftserials.Serialnum_ID)
WHERE
(85 = aircraftserials.Aircraft_ID AND serial IS NOT NULL)
我想消除这些变量并将其作为子查询,
我认为我需要CTE;最终结果必须是
MDS, concatenated serials
我已经尝试过此帖子,但无法完全理解 Simplify CTE string concatenation?
这是数据样本
CREATE TABLE TestBed
(
Aircraft_ID INT,
Serial VARCHAR(50),
MDS VARCHAR(50)
)
INSERT INTO TestBed (Aircraft_ID, Serial, MDS)
VALUES (85, '56-1965', 'T-37B'),
(85, '56-1967', 'T-37B'),
(85, '56-3547', 'T-37B'),
(85, '56-3577', 'T-37B'),
(85, '57-2265', 'T-37B'),
(85, '57-2272', 'T-37B'),
(85, '58-1915', 'T-37B'),
(85, '58-1925', 'T-37B'),
(85, '59-0249', 'T-37B'),
(85, '59-0273', 'T-37B'),
(85, '59-0299', 'T-37B')
select * from TestBed
答案 0 :(得分:1)
我认为您不是在寻找CTE,而是在寻找带有字符串连接的聚合。在SQL Server中,可以使用子查询FOR XML
完成。
SELECT tb1.aircraft_id,
stuff((SELECT concat(', ', tb2.serial)
FROM testbed tb2
WHERE tb2.aircraft_id = tb1.aircraft_id
AND tb2.mds = tb1.mds
FOR XML PATH ('')), 1, 2, '') serial,
tb1.mds
FROM testbed tb1
GROUP BY tb1.aircraft_id,
tb1.mds;
顺便说一句:如果mds
对于每架飞机来说总是相同的,那么它不应该在testbed
中,而应该在飞机表中。
答案 1 :(得分:0)
我根据您的测试数据提出了一个递归CTE
;with ForceId as
(SELECT ROW_NUMBER() OVER(partition by MDS order by serial) as RN,* FROM TestBed),
RECURS as
(SELECT f.MDS,f.RN,f.Serial, cast(f.serial as nvarchar(max)) as x FROM ForceId F WHERE F.RN = 1
UNION ALL
SELECT f2.mds,f2.rn, r.Serial,r.x + ', ' + f2.Serial FROM ForceId F2
JOIN RECURS R
ON F2.mds = R.mds
AND R.RN + 1 = F2.rn
)
SELECT MDS, x FROM
recurs r where r.rn =
(select max(r2.rn) from recurs r2 where r.MDS = r2.mds)