[英]How to “roll up” rows on matching column data and create new columns for non-matching data in SQL server
我正在尋找有關如何“上卷”或合並數據庫中與特定列值匹配的行並為不匹配的數據創建新列的方向。 我只是在尋找方向,而不是確切的解決方案。 我正在使用SSMS 2014。
例如,我有一個查詢,它輸出如下數據集:
fld1 fld2 fld3 fld4 fld5
---------------------------------------
row1 1 2 3 4 text1
row2 1 2 3 4 text2
row3 1 2 3 4 text3
我想操縱輸出對此:
fld1 fld2 fld3 fld4 fld5 fld6 fld7
------------------------------------------------------------
row1 1 2 3 4 text1 text2 text3
同樣,我只是在尋找方向,例如,研究使用PIVOT或FOR XML或RECURSIVE CTE,而不是確切的解決方案,因為我仍在學習中。 謝謝。
根據您的樣本數據
SELECT Col1, Col2, Col3, Col4, MAX(Col5) Col5
FROM
(
VALUES
(1, 2, 3, 4, 'text1'),
(1, 2, 3, 4, 'text2'),
(1, 2, 3, 4, 'text3')
) T(Col1, Col2, Col3, Col4, Col5)
GROUP BY Col1,
Col2,
Col3,
Col4;
將返回:
+------+------+------+------+-------+
| Col1 | Col2 | Col3 | Col4 | Col5 |
+------+------+------+------+-------+
| 1 | 2 | 3 | 4 | text3 |
+------+------+------+------+-------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.