First, the person who stores your data is a mess. I would recommend reading good data structures and correcting yours if possible. Here's a TSQL query that will deliver you the data in the correct format.
WITH CTE_no_nums AS ( SELECT docID, CASE WHEN PATINDEX('%[0-9]%',column1) > 0 THEN SUBSTRING(column1,0,PATINDEX('%[0-9]%',column1)) ELSE column1 END AS cols, COALESCE(column2,column3) AS vals FROM miscValues WHERE column2 IS NOT NULL OR column3 IS NOT NULL ), CTE_Pivot AS ( SELECT docID,partNumber,prio,[length],material FROM CTE_no_nums PIVOT ( MAX(vals) FOR cols IN (partNumber,prio,[length],material) ) pvt ) SELECT A.docId + ' # ' + B.vals AS [DocID
Results:
DocID # Plant docID partNumber prio Plant Identification length colors ---------------- ------ ---------- ---- ---------- ------------------ ------- ------------------------- D0001 # PlantB D0001 X001 1 PlantB X001#MA123#10.87 10.87 white,black,blue D0001 # PlantC D0001 X001 1 PlantC X001#MA123#10.87 10.87 white,black,blue D0002 # PlantA D0002 X002 2 PlantA X002#MA456#16.43 16.43 black,yellow D0002 # PlantC D0002 X002 2 PlantC X002#MA456#16.43 16.43 black,yellow D0002 # PlantD D0002 X002 2 PlantD X002#MA456#16.43 16.43 black,yellow
source share