在SQL Server 中使用STRING_AGG 的不同值
SQL Server 2017 中的STRING_AGG 函數可讓您將值連接到單一字串中。但是,當連接多次出現的欄位時,它可能會傳回重複值。
考慮以下查詢:
SELECT ProjectID, STRING_AGG( newID.value, ',') WITHIN GROUP (ORDER BY newID.value) AS NewField FROM [dbo].[Data] WITH(NOLOCK) CROSS APPLY STRING_SPLIT([bID],';') AS newID WHERE newID.value IN ('O95833', 'Q96NY7-2') GROUP BY ProjectID ORDER BY ProjectID
此查詢傳回連接的值,但包含重複值:
ProjectID | NewField |
---|---|
2 | O95833,O95833,O95833,Q96NY7-2,Q96NY7-2,Q96NY7-2 |
4 | Q96NY7-2,Q96NY7-2 |
若要只擷取唯一值,請在子查詢:
SELECT ProjectID ,STRING_AGG(value, ',') WITHIN GROUP (ORDER BY value) AS NewField FROM ( SELECT DISTINCT ProjectID , newId.value FROM [dbo].[Data] WITH (NOLOCK) CROSS APPLY STRING_SPLIT([bID],';') AS newId WHERE newId.value IN ( 'O95833' , 'Q96NY7-2' ) ) x GROUP BY ProjectID ORDER BY ProjectID
此子查詢在應用STRING_AGG 函數之前刪除重複項。最終結果是:
ProjectID | NewField |
---|---|
2 | O95833, Q96NY7-2 |
4 | Q96NY7-2 |
以上是如何在 SQL Server 中使用 STRING_AGG 取得不同的值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!