65.9K
CodeProject is changing. Read more.
Home

Stupid CTE tricks -- string concatenation

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jan 3, 2012

CPOL
viewsIcon

9528

Pretty cool little trick you've made there.With the help of an analytic function, I've fixed the ordering, and as a byproduct it also scales better:WITH ranked AS ( SELECT make,model,Rank() over (PARTITION BY make ORDER BY model) Rnk FROM MakeModel ),cte...

Pretty cool little trick you've made there. With the help of an analytic function, I've fixed the ordering, and as a byproduct it also scales better:
WITH ranked AS (
    SELECT  make,model,Rank() over (PARTITION BY make ORDER BY model) Rnk 
    FROM    MakeModel
    )
,cte (make,models,rnk) AS
    (
    SELECT  Make
           ,Model Models
           ,rnk
    FROM    ranked
    WHERE   rnk = 1
    UNION ALL
    SELECT  cte.Make
           ,Models + N' , ' + Model
           ,r.Rnk
    FROM cte
    INNER JOIN ranked r
    ON cte.Make=r.Make
    AND cte.Rnk = r.rnk - 1
    )
SELECT Make,Max(Models) models,Max(rnk) cnt FROM cte GROUP BY make ORDER BY make