sql >> Database teknologi >  >> RDS >> Sqlserver

SQL Server 2008 opdeler, sorter og flet værdi

;WITH cte(car_Id, traceXML) AS
 (
  SELECT car_Id, CAST('<A>' + REPLACE(trace, ';', '</A><A>') + '</A>' AS XML)
  FROM dbo.cars
  ), cte2 AS
 (
  SELECT car_Id, trace, NTILE(4) OVER(ORDER BY (SELECT 1)) AS grId  
  FROM cte
  CROSS APPLY (SELECT Tbl.Col.value('.', 'nvarchar(250)') AS trace 
               FROM traceXML.nodes('/A') Tbl(Col)) AS List
  ), cte3 AS
 (
  SELECT DISTINCT a.car_Id,(
  SELECT ISNULL(b.trace, '') + ';' 
  FROM cte2 b 
  WHERE b.grId = a.grId
  FOR XML PATH('')) AS trace
  FROM cte2 a
  )
  SELECT DISTINCT a.car_Id,(
  SELECT ISNULL(b.trace, '')
  FROM cte3 b
  WHERE b.car_Id = a.car_Id
  FOR XML PATH('')) AS trace
  FROM cte3 a

Demo på SQLFiddle



  1. tilpasse pager i psql

  2. jQuery Connected Sorterbare lister, Gem ordre til MySQL

  3. Sådan henter du nøjagtige matchende poster i Spring JPA @Query

  4. PHP:mysql v mysqli v pdo