1

我想根據ID將值連接成一列。如何在SQL 2012中使用來自不同列的值連接名稱

有沒有辦法用SQL語句連接基於另一列的兩列?

我的表看起來像這樣

customerID Name Values 
1   John 10apples 
1   John 20oranges 
1   John 30bananas 
2   Steve 15apples 
2   Steve 20oranges 
2   Steve 35bananas 

我希望查詢應該給我一些這樣的事

customerID Name Values  FAKENAME 
1   John 10apples 10apples_20oranges_30bananas 
1   John 20oranges 
1   John 30bananas 
2   Steve 15apples 15apples_20oranges_35bananas 
2   Steve 20oranges 
2   Steve 35bananas 

基本上是不同的IDS應該結合值創建法米克名

+0

的可能的複製(https://stackoverflow.com/questions/10404348/sql -server-dynamic-pivot-query) –

+0

[如何使用GROUP BY連接SQL Server中的字符串?](https://stackoverflow.com/questions/273238/how-to-use-group-by- to-concatenate-strings-in-sql-server) –

回答

1

你可以使用這個。

DECLARE @Table TABLE (CustomerID INT, Name VARCHAR(20), [Values] VARCHAR(20)) 
INSERT INTO @Table 
VALUES 
(1 ,'John','10apples'), 
(1 ,'John','20oranges'), 
(1 ,'John','30bananas'), 
(2 ,'Steve','15apples'), 
(2 ,'Steve','20oranges'), 
(2 ,'steve','35bananas') 

;WITH CTE 
    AS (
    SELECT DISTINCT 
      CustomerID, 
      Name, 
      [Values], 
      STUFF(
       (
        SELECT '_'+[Values] 
        FROM @Table T2 
        WHERE T1.CustomerID = T2.CustomerID FOR XML PATH('') 
       ), 1, 1, '') FakeName 
    FROM @Table T1) 
    SELECT CustomerID, 
      Name, 
      [Values], 
      CASE 
       WHEN(ROW_NUMBER() OVER(PARTITION BY FakeName ORDER BY FakeName)) > 1 
       THEN '' 
       ELSE FakeName 
      END FakeName 
    FROM CTE; 

結果:

customerID Name Values  FAKENAME 
1   John 10apples 10apples_20oranges_30bananas 
1   John 20oranges 
1   John 30bananas 
2   Steve 15apples 15apples_20oranges_35bananas 
2   Steve 20oranges 
2   Steve 35bananas 
+0

更新了我的答案。 –

0

試試這個:?SQL Server的動態PIVOT查詢]

;WITH cte0 AS(  
SELECT 1 AS CustomerID, 'John' AS [Name],'10apples' AS [Values] UNION 
SELECT 1 ,    'John'   ,'20oranges'   UNION 
SELECT 1 ,    'John'   ,'30bananas'   UNION 
SELECT 2 ,    'Steve'   ,'15strawberries'  UNION 
SELECT 2 ,    'Steve'   ,'25blueberries'  UNION 
SELECT 2 ,    'steve'   ,'35blackberries') 

,cte1 as(
SELECT customerid,[name], 
     STUFF((SELECT '_'+ [values] 
       FROM cte0 t1 
       WHERE t1.customerid = t2.customerid 
       FOR XML PATH ('')), 1, 1, '') AS FakeName 
FROM cte0 t2 
GROUP BY customerid,[name]), 

cte2 AS(
SELECT a.CustomerID,a.name,[values],fakename,Row_Number() OVER(PARTITION BY a.CustomerID ORDER BY a.CustomerID) AS RN 
FROM cte0 a 
    INNER JOIN cte1 b 
     ON a.CustomerID = b.customerid) 

SELECT CustomerID,[name],[values],CASE WHEN rn = 1 THEN FakeName ELSE '' END AS FakeName 
FROM cte2 
相關問題