2015-09-29 94 views
0

我有列用戶名國家或地區名稱表轉換行到列

現在我想以這種方式獲取記錄

[UserId] [ContryName1] [ContryName2] [ContryName3]......... 
+1

使用'PIVOT'我只是寫一個[** **答案(http://stackoverflow.com/questions/32849539/sql-server-populate -a-table-based-another-table-with-a-substring-as-column-na/32849645)非常類似於這種情況。在我的情況下,我知道列前的名稱,如果你不需要[** dinamic pivot **](http://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query ) –

回答

2

小提琴這裏:http://sqlfiddle.com/#!6/cd6f1/1

DECLARE @SQL AS NVARCHAR(MAX) 
WITH CTE AS 
(
SELECT USERID,COUNTRYNAME,ROW_NUMBER() OVER(PARTITION BY USERID ORDER BY COUNTRYNAME) AS RN 
FROM CNTRIES 
) 

SELECT @SQL = 'WITH CTE1 AS 
(
SELECT USERID,COUNTRYNAME,ROW_NUMBER() OVER(PARTITION BY USERID ORDER BY COUNTRYNAME) AS RN 
FROM CNTRIES 
) 
SELECT * 
FROM 
(SELECT USERID,COUNTRYNAME,RN FROM CTE1)C 
PIVOT (MAX(COUNTRYNAME) FOR RN IN (['+STUFF((SELECT '],['+CAST(RN AS VARCHAR(100)) 
              FROM CTE 
              GROUP BY RN 
              FOR XML PATH('')),1,3,'')+'])) AS PIVOTT' 
0

PIVOT是,如果你最好的選擇您的版本是SQL Server 2005或更高版本,但是您沒有聲明版本,並且嘗試在沒有自然聚合的情況下使用PIVOT可能難以掌握。如果您的版本低於2005年,則會出現更大的問題。否則,您需要在表格本身上加入以提供相同的結果。您可以使用排名功能使其更容易一些。像這樣的東西雖然效率低下,但會產生類似的結果。

/* 
    IF OBJECT_ID('Countries','U') IS NOT NULL 
     DROP TABLE Countries 

    CREATE TABLE Countries 
    (
      UserID INT 
     , CountryName VARCHAR(255) 
    ) 

    INSERT Countries 
    VALUES (1, 'India') 
     , (1, 'UK') 
     , (2, 'USA') 
     , (2, 'India') 
     , (2, 'Canada') 
    */ 


    SELECT DISTINCT x.UserID, x.CountryName Country1, y.CountryName Country2, z.CountryName Country3 
    FROM Countries c 
     LEFT JOIN 
     (
      SELECT *, RANK() OVER(PARTITION BY UserID ORDER BY UserID, CountryName) AS UserRank 
      FROM Countries 
     )x ON x.UserID = c.UserID AND x.UserRank=1 
     LEFT JOIN 
     (
      SELECT *, RANK() OVER(PARTITION BY UserID ORDER BY UserID, CountryName) AS UserRank 
      FROM Countries 
     )y ON y.UserID = c.UserID AND y.UserRank=2 
     LEFT JOIN 
     (
      SELECT *, RANK() OVER(PARTITION BY UserID ORDER BY UserID, CountryName) AS UserRank 
      FROM Countries 
     )z ON z.UserID = c.UserID AND z.UserRank=3 
+0

我正在使用sql sever 2012。 –