Breaking News
Loading...
14/04/2014

Convert column thành row trong SQL Server

--Trước tiên tạo dữ liệu mẫu
IF OBJECT_ID ('dbo.Players') IS NOT NULL
    DROP TABLE dbo.Players;
 
CREATE TABLE dbo.Players
(
      PlayerID INT
    , Win INT
    , Defeat INT
    , StandOff INT
    , CONSTRAINT PK_Players PRIMARY KEY CLUSTERED (PlayerID) ON [PRIMARY]
);
INSERT INTO dbo.Players (PlayerID, Win, Defeat, StandOff)
VALUES
    (1, 7,  6,  9),
    (2, 12, 5,  0),
    (3, 3,  11, 1);

--Đây là câu lệnh để unpivot
SELECT t.*
FROM dbo.Players
CROSS APPLY (
    VALUES
          (PlayerID, Win,      'Win')
        , (PlayerID, Defeat,   'Defeat')
        , (PlayerID, StandOff, 'StandOff')
) t(PlayerID, GameCount, GameType)

http://blog.devart.com/is-unpivot-the-best-way-for-converting-columns-into-rows.html
http://blogs.msdn.com/b/spike/archive/2009/03/03/pivot-tables-in-sql-server-a-simple-sample.aspx
http://www.mssqltips.com/sqlservertip/1019/crosstab-queries-using-pivot-in-sql-server/

0 comments:

Post a Comment

 
Toggle Footer