使用CTE或公用表表达式,如何跨多行连接字符串。
答案 0 :(得分:0)
WITH NumberedCounties(RowNumber, County, State)
AS (SELECT ROW_NUMBER() OVER (PARTITION BY C.State ORDER BY c.County),
c.County,
c.State
FROM Static.County C
),
JoinedCounties(RowNumber, Counties, State)
AS (SELECT RowNumber,
CONVERT(VARCHAR(4000), County),
State
FROM NumberedCounties
WHERE RowNumber = 1
UNION ALL
SELECT C.RowNumber,
CONVERT(VARCHAR(4000), R.Counties + ', '
+ C.County),
C.State
FROM JoinedCounties R
INNER JOIN NumberedCounties C ON R.State = C.State
AND C.RowNumber = (R.RowNumber
+ 1)
),
WithMax(Counties, State, RowNumber, MaxRowNumber)
AS (SELECT Counties,
State,
RowNumber,
MAX(RowNumber) OVER (PARTITION BY State) AS MaxRowNumber
FROM JoinedCounties
)
SELECT Counties,
State
FROM WithMax
WHERE RowNumber = MaxRowNumber
OPTION (MAXRECURSION 500);
注意:如果你有一些非常重要的记录,那么与在应用程序中连接记录相比,这将会非常慢。