Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Tukar Beberapa Baris ke Kolom di SQL Server 2008

Mungkin seperti ini:

Pertama data uji:

CREATE TABLE #tbl (AccountManager VARCHAR(100), Action VARCHAR(100),Count INT)

INSERT INTO #tbl
VALUES
    ('Joe','Client Negotiation',10),
    ('Bloggs','Closing',1),
    ('Aunty','Email',12),
    ('Marie','Preparing Contract',32)

Jika Anda tahu bahwa kolomnya statis. Kemudian Anda dapat melakukan ini:

SELECT
    AccountManager,
    ISNULL([Client Negotiation],0) AS [Client Negotiation],
    ISNULL([Closing],0) AS [Closing],
    ISNULL([Email],0) AS [Email],
    ISNULL([Preparing Contract],0) AS [Preparing Contract]
FROM
(
SELECT
    tbl.AccountManager,
    tbl.Action,
    tbl.Count
FROM
    #tbl AS tbl
) AS p
PIVOT
(
    SUM([Count])
    FOR [Action] IN([Client Negotiation],[Closing],[Email],[Preparing Contract])
) AS pvt

Jika tidak, Anda harus melakukan pivot dinamis seperti ini:

Pertama nama kolom unik:

DECLARE @cols VARCHAR(MAX),
        @colsWithIsNull VARCHAR(MAX)
;WITH CTE
AS
(
    SELECT
        ROW_Number() OVER(PARTITION BY tbl.Action ORDER BY tbl.Action) AS iRank,
        tbl.Action
    FROM
        #tbl AS tbl
)
SELECT  @cols = COALESCE(@cols + ','+QUOTENAME(Action),
                     QUOTENAME(Action)),
        @colsWithIsNull=COALESCE(@colsWithIsNull + ',ISNULL('+QUOTENAME(Action)+',0) AS '+QUOTENAME(Action),
                     'ISNULL('+QUOTENAME(Action)+',0) AS '+QUOTENAME(Action))
FROM
    CTE
WHERE
    iRank=1

Kemudian pivot dinamis seperti ini:

DECLARE @query NVARCHAR(4000)=
N'SELECT
    AccountManager,
    '[email protected]+'
FROM
(
SELECT
    tbl.AccountManager,
    tbl.Action,
    tbl.Count
FROM
    #tbl AS tbl
) AS p
PIVOT
(
    SUM([Count])
    FOR [Action] IN('[email protected]+')
) AS pvt'

EXECUTE(@query)

Kemudian dalam kasus saya, saya akan menjatuhkan tabel temp:

DROP TABLE #tbl


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Bagaimana saya bisa mengubah data Geometri menjadi data Geografi di MS SQL Server 2008?

  2. Mengapa ISNUMERIC('.') mengembalikan 1?

  3. Pengembangan Mesin Virtual Azure untuk Penggunaan SQL Server

  4. bandingkan nilai yang dipisahkan koma di sql

  5. Cara Menganalisis Aktivitas Satu Database di SQL Server