sql >> Database teknologi >  >> RDS >> Sqlserver

Skift nogle rækker ud i kolonner i SQL Server 2008

Måske noget som dette:

Først testdataene:

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)

Hvis du ved, at kolonnerne er statiske. Så kan du gøre dette:

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

Ellers skal du lave en dynamisk pivot som denne:

Først de unikke kolonnenavne:

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

Så den dynamiske pivot som denne:

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)

Så i mit tilfælde vil jeg droppe vikartabellen:

DROP TABLE #tbl


  1. Sådan skriver du joinforespørgsel i Volusion API

  2. Sådan viser du alle tabelnavne fra en bestemt mysql-database i php

  3. ORA-30926:ude af stand til at få et stabilt sæt rækker i kildetabellerne

  4. VÆLG COUNT() vs mysql_num_rows();