我必須處理從ERP系統到MySQL數據庫的映射。這是目前在ERP系統中的結構是:使用PIVOT表的動態SQL中的字符串連接
_____________________________________
| Article | Feature | Criterion |
|---------|---------------|-----------|
| Art1 | size | 4*10 |
| Art1 | color | red |
| Art1 | functionality | doesA |
| Art1 | ... | ... |
| Art2 | size | 2*5 |
| Art2 | color | green |
| Art2 | functionality | doesB |
| Art2 | ... | ... |
-------------------------------------
什麼,我需要做的是地圖像這樣:
________________________________________________
| Article | size | color | functionality | ... |
|---------|------|-------|---------------|-------|
| Art1 | 4*10 | red | doesA | ... |
| Art2 | 2*5 | green | doesB | ... |
------------------------------------------------
我可以通過訪問ERP系統T-SQL並且可以執行工作的動態查詢,該查詢爲我提供了一個表格,如下所示:
DECLARE @cols AS nvarchar(MAX),
@query AS nvarchar(MAX)
SELECT @cols = stuff((SELECT DISTINCT ', ' + quotename(f.Feature) + ''
FROM CRITERION c, FEATURE f
WHERE --necessary joins
FOR xml PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @query = N'SELECT Article, ' + @cols + N'
FROM (
SELECT Article, Feature, Criterion
FROM --necessary tables
WHERE --necessary joins
) x
pivot
(
max(Criterion)
FOR Feature IN (' + @cols + N')
) p
'
EXEC sp_executesql @query;
,現在快到了的問題,該系統具有多項選擇的一些特點:
_____________________________________
| Article | Feature | Criterion |
|---------|---------------|-----------|
| Art3 | color | red |
| Art3 | color | green |
-------------------------------------
和查詢只是給我的第一個結果在表。
________________________________________
| Article | size | color | functionality |
|---------|------|-------|---------------|
| Art3 | ... | red | ... |
----------------------------------------
所以我的問題是,如果有任何的方式來添加一個字符串連接無論是在子查詢「X」或數據透視表中「P」,所以結果就變成如下:
_____________________________________________
| Article | size | color | functionality |
|---------|------|------------|---------------|
| Art3 | ... | red, green | ... |
---------------------------------------------