TSQL – 查看交叉应用和主键

这是我的基础表:

docID | rowNumber | Column1 | Column2 | Column3 

我使用交叉应用和透视来将Column1中的logging转换为实际列,并将列2和列3中的值用作新列的logging。 在我的小提琴中,你可以看到基地和转换select语句。

我有像植物和颜色这些列的编号,例如Plant1,Plant2,Plant3,Color1,Color2等

对于所有工厂列中存在的每个工厂,我想要在一个列中创build一个以逗号分隔的颜色列表的新行。

我想要实现的也是在下面的截图:

输入输出

这应该成为在Excel中使用的视图。 我如何修改视图以获得所需的结果?

附加问题:长度列是数字。 有什么办法可以从Excel内切换小数分隔符作为用户,并将其应用到这个或所有数字列,以便它可以被Excel识别为一个数字? 我曾经有一个旧的PHPnetworking查询,我会通过从Excel中的下拉单元格作为参数分隔符。

谢谢。

首先,数据存储的方式是一团糟。 我会build议读好数据结构,如果可以的话,修复你的数据结构。 这是一个TSQL查询,以正确的格式获取数据。

 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 # Plant], A.docID, A.partNumber, A.prio, B.vals AS Plant, A.partNumber + '#' + A.material + '#' + A.[length] AS Identification, A.[length], SUBSTRING(CA.colors,0,LEN(CA.colors)) colors --substring removes last comma FROM CTE_Pivot A INNER JOIN CTE_no_nums B ON A.docID = B.docID AND B.cols = 'Plant' CROSS APPLY ( SELECT vals + ',' FROM CTE_no_nums C WHERE cols = 'Color' AND C.docID = A.docID FOR XML PATH('') ) CA(colors) 

结果:

 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