2015-10-20 76 views
0

是否有更好的方法來實現下表中的PIVOT - 基本上我試圖計算typeid的永遠userid,以及獲得每種類型的第一個值,並將類型和值(使用SQL Server 2012):PIVOT兩列

enter image description here

這是預期的結果:

enter image description here

這裏就是我想出了:

SELECT userid , 
     MAX([1]) [1] , 
     MAX([2]) [2] , 
     MAX(value1) [value1] , 
     MAX(value2) [value2] 
FROM (SELECT userid , 
        typeid , 
        FIRST_VALUE(value) OVER (PARTITION BY userid, typeid ORDER BY testid) [value] , 
        'value' + CONVERT(VARCHAR(20), typeid) [valuepivot] 
      FROM  dbo.test 
     ) t PIVOT(COUNT(typeid) FOR typeid IN ([1], [2])) as pivottype 
     PIVOT(MAX(value) FOR [valuepivot] IN ([value1], [value2])) as pivottype2 
GROUP BY userid 

表模式:

CREATE TABLE [dbo].[Test](
      PIVOT(MAX(value) FOR [valuepivot] IN ([value1], [value2])) as pivottype2 
    [TestID] [int] PRIMARY KEY IDENTITY(1,1) , 
    [UserID] [int] NOT NULL, 
    [TypeID] [int] NOT NULL, 
    [Value] [varchar](100) NOT NULL 
) 
    GROUP BY userid 
+0

看來您的代碼目前正常工作,而您正在尋求改進它。通常,這些問題都太自以爲是了這個網站,但你可能會發現更好的運氣在[CodeReview.SE(http://codereview.stackexchange.com/tour)。請記住閱讀[他們的要求](http://codereview.stackexchange.com/help/on-topic),因爲它們比這個網站更嚴格。 –

回答

0

我只想做到這一點使用條件彙總:

select userid, 
     sum(case when typeid = 1 then 1 else 0 end) as test1, 
     sum(case when typeid = 2 then 1 else 0 end) as test2, 
     max(case when typeid = 1 then value end) as test1, 
     max(case when typeid = 2 then value end) as test2 
from (select t.*, 
      row_number() over (partition by userid, typeid order by testid) as seqnum 
     from test 
    ) t 
group by userid; 

無論是簡單與否見仁見智。