Aiuto con la query PIVOT


12

Ho una tabella con la struttura seguente:

CREATE TABLE [dbo].[AUDIT_SCHEMA_VERSION](
    [SCHEMA_VER_MAJOR] [int] NOT NULL,
    [SCHEMA_VER_MINOR] [int] NOT NULL,
    [SCHEMA_VER_SUB] [int] NOT NULL,
    [SCHEMA_VER_DATE] [datetime] NOT NULL,
    [SCHEMA_VER_REMARK] [varchar](250) NULL
);

alcuni dati di esempio (sembra un problema con sqlfiddle .. quindi inserendo alcuni dati di esempio):

INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,6,13,CAST('20130405 04:41:25.000' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,6,13,CAST('20130405 04:41:25.000' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,7,13,CAST('20130405 04:41:25.000' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,10,13,CAST('20130405 04:41:25.000' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,12,13,CAST('20130405 04:41:25.000' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,12,13,CAST('20130405 04:41:25.000' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,16,13,CAST('20130405 04:41:25.000' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,16,13,CAST('20130405 04:41:25.000' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,16,13,CAST('20130405 04:41:25.000' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,16,13,CAST('20140417 18:10:44.100' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(2,5,0,CAST('20140417 18:14:14.157' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(2,6,0,CAST('20140417 18:14:23.327' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(2,7,0,CAST('20140417 18:14:32.270' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(2,8,0,CAST('20141209 09:38:40.700' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(2,9,0,CAST('20141209 09:43:04.237' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(2,10,0,CAST('20141209 09:45:19.893' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(2,13,0,CAST('20150323 14:54:30.847' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,10,13,CAST('20130405 04:41:25.000' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,16,14,CAST('20140417 18:11:07.977' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,16,15,CAST('20140417 18:11:13.130' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(2,2,0,CAST('20140417 18:12:11.200' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(2,3,0,CAST('20140417 18:12:33.330' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(2,4,0,CAST('20140417 18:12:48.803' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,13,13,CAST('20130405 04:41:25.000' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(1,16,13,CAST('20130405 04:41:25.000' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(2,11,0,CAST('20141209 09:45:58.993' as DATETIME),'Stored procedure build')
INSERT INTO [AUDIT_SCHEMA_VERSION]([SCHEMA_VER_MAJOR],[SCHEMA_VER_MINOR],[SCHEMA_VER_SUB],[SCHEMA_VER_DATE],[SCHEMA_VER_REMARK])
VALUES(2,12,0,CAST('20141209 09:46:50.070' as DATETIME),'Stored procedure build');

Ecco il SQLFiddlecon alcuni dati di esempio.

Qualcuno con una competenza T-sql può guidarmi su come ottenere il risultato finale? So che PIVOT(con colonne dinamiche) sarà l'approccio giusto, ma non riesco a capirlo.

Risultati aspettati :

inserisci qui la descrizione dell'immagine

Finora ho di seguito:

select row_number() over (
        partition by CONVERT(varchar(10), SCHEMA_VER_DATE, 110) order by SCHEMA_VER_DATE 
        ) as rownum
    ,CONVERT(varchar(10), SCHEMA_VER_DATE, 110) as UPG_DATE
    ,CONVERT(varchar(1), SCHEMA_VER_MAJOR) + '.' + CONVERT(varchar(2), SCHEMA_VER_MINOR) + '.' + CONVERT(varchar(2), SCHEMA_VER_SUB) as SCHEMA_VER
from audit_schema_version
where SCHEMA_VER_REMARK like 'Stored procedure build'
order by UPGRADE_DATE 

inserisci qui la descrizione dell'immagine

Risposte:


20

Questo è un po 'disordinato per ottenere il risultato finale perché ne hai multipli SCHEMA_VERper ogni data. Prima di dimostrare come eseguire questa operazione con SQL dinamico, mostrerò innanzitutto come farlo con codice statico per ottenere la logica corretta. Per ottenere il risultato finale è possibile utilizzare sia pivot che unpivot.

Ma prima, cambierei la tua query originale per usare quanto segue:

select 
    row_number() over (
    partition by CONVERT(varchar(10), SCHEMA_VER_DATE, 110) order by SCHEMA_VER_MAJOR, SCHEMA_VER_MINOR, SCHEMA_VER_SUB
    ) as minrownum
, row_number() over (
    partition by CONVERT(varchar(10), SCHEMA_VER_DATE, 110) order by SCHEMA_VER_MAJOR desc, SCHEMA_VER_MINOR desc, SCHEMA_VER_SUB desc
    ) as maxrownum
,CONVERT(varchar(10), SCHEMA_VER_DATE, 110) as UPG_DATE
,CONVERT(varchar(1), SCHEMA_VER_MAJOR) + '.' + CONVERT(varchar(2), SCHEMA_VER_MINOR) + '.' + CONVERT(varchar(2), SCHEMA_VER_SUB) as SCHEMA_VER
from audit_schema_version
where SCHEMA_VER_REMARK like 'Stored procedure build';

Vedi SQL Fiddle with Demo . Ero solito row_number()ottenere il primo e l'ultimo SCHEMA_VERper ogni data. Questo è necessario in modo da poter concatenare solo quei valori insieme per il commento.

Quindi userei una tabella temporanea per memorizzare le righe che hanno un minrownume maxrownumdi 1. La tabella temporanea conterrebbe il upg_datee il comment. Questa colonna di commento contiene una stringa concatenata della coppia di SCHEMA_VERper ogni data.

create table #srcData
(
    upg_date varchar(10),
    comment varchar(500)
);

Il codice per popolare la tabella temporanea sarebbe quindi:

;with cte as
(
  select 
        row_number() over (
        partition by CONVERT(varchar(10), SCHEMA_VER_DATE, 110) order by SCHEMA_VER_MAJOR, SCHEMA_VER_MINOR, SCHEMA_VER_SUB
        ) as minrownum
    , row_number() over (
        partition by CONVERT(varchar(10), SCHEMA_VER_DATE, 110) order by SCHEMA_VER_MAJOR desc, SCHEMA_VER_MINOR desc, SCHEMA_VER_SUB desc
        ) as maxrownum
    ,CONVERT(varchar(10), SCHEMA_VER_DATE, 110) as UPG_DATE
    ,CONVERT(varchar(1), SCHEMA_VER_MAJOR) + '.' + CONVERT(varchar(2), SCHEMA_VER_MINOR) + '.' + CONVERT(varchar(2), SCHEMA_VER_SUB) as SCHEMA_VER
  from audit_schema_version
  where SCHEMA_VER_REMARK like 'Stored procedure build'
)
insert into #srcData
select distinct
    c1.UPG_DATE,
    comment 
        = STUFF((
                  SELECT ' - ' + c2.SCHEMA_VER 
                  FROM cte c2
                  WHERE (c2.minrownum = 1 or c2.maxrownum = 1)
                    and c1.upg_date = c2.upg_date
                  order by c2.minrownum
                  FOR XML PATH(''), TYPE).value('.[1]', 'nvarchar(max)'), 1, 2, '') 
from cte c1
where c1.minrownum = 1 or c1.maxrownum = 1;

Questo primo passaggio attraverso i tuoi dati ti dà:

|   upg_date |           comment |
|------------|-------------------|
| 03-23-2015 |            2.13.0 |
| 04-05-2013 |  1.6.13 - 1.16.13 |
| 04-17-2014 |   1.16.13 - 2.7.0 |
| 12-09-2014 |    2.8.0 - 2.12.0 |

Ora è ancora necessario ottenere un conteggio di ciascuna data per l'anno e il commento completo concatenato. Questo sarebbe dove entra in gioco unpivot. È possibile utilizzare il codice seguente per creare il commento completo per ogni anno e ottenere il conteggio.

select distinct 
    Yr =  right(s1.upg_date, 4),
    cnt = count(*) over(partition by right(s1.upg_date, 4)),
    fullcomment 
            = STUFF((
                      SELECT '; ' + s2.comment 
                      FROM #srcData s2
                      WHERE right(s1.upg_date, 4) = right(s2.upg_date, 4)
                      FOR XML PATH(''), TYPE).value('.[1]', 'nvarchar(max)'), 1, 2, '') 
from #srcData s1;

Vedi SQL Fiddle with Demo . I dati ora sembrano:

|   Yr | cnt |                       fullcomment |
|------|-----|-----------------------------------|
| 2013 |   1 |                  1.6.13 - 1.16.13 |
| 2014 |   2 |  1.16.13 - 2.7.0;  2.8.0 - 2.12.0 |
| 2015 |   1 |                            2.13.0 |

Come si può vedere che hai più colonne che devono essere ruotato, in modo da poter UNPIVOT sia l' fullcommente cntcolonna in più righe. Questo può essere fatto usando la funzione UNPIVOT o CROSS APPLY. Preferirei fare domanda incrociata qui perché vorrai concatenare i valori insieme per creare i nomi delle nuove colonne:

;with cte as
(
    select distinct 
        Yr =  right(s1.upg_date, 4),
        cnt = count(*) over(partition by right(s1.upg_date, 4)),
        fullcomment 
                = STUFF((
                          SELECT '; ' + s2.comment 
                          FROM #srcData s2
                          WHERE right(s1.upg_date, 4) = right(s2.upg_date, 4)
                          FOR XML PATH(''), TYPE).value('.[1]', 'nvarchar(max)'), 1, 2, '') 
    from #srcData s1
) 
select [2015], [2015_comment], [2014], [2014_comment], [2013], [2013_comment]
from
(
    select c.col, val
    from cte d
    cross apply
    (
        values 
            (Yr, cast(cnt as nvarchar(50))),
            (Yr+'_comment', fullcomment)
    ) c (col, val)  
) d
pivot
(
    max(val)
    for col in ([2015], [2015_comment], [2014], [2014_comment], [2013], [2013_comment])
) piv;

Vedi SQL Fiddle with Demo .

Una volta ottenuta la logica, puoi facilmente convertirla in SQL dinamico.

-- get list of the columns
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT  ',' + QUOTENAME(col) 
                    from #srcData
                    cross apply
                    (
                        select right(upg_date, 4), right(upg_date, 4), 2 union all
                        select right(upg_date, 4), right(upg_date, 4)+'_comment', 1
                    ) c (yr, col, so)
                    group by yr, col, so
                    order by yr desc, so desc
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query 
    = 'SELECT ' + @cols + ' 
        from 
        (
            select c.col, val
            from
            (
                select distinct 
                    Yr =  right(s1.upg_date, 4),
                    cnt = count(*) over(partition by right(s1.upg_date, 4)),
                    fullcomment 
                            = STUFF((
                                      SELECT ''; '' + s2.comment 
                                      FROM #srcData s2
                                      WHERE right(s1.upg_date, 4) = right(s2.upg_date, 4)
                                      FOR XML PATH(''''), TYPE).value(''.[1]'', ''nvarchar(max)''), 1, 2, '''') 
                from #srcData s1
            ) d
            cross apply
            (
                values 
                    (Yr, cast(cnt as nvarchar(50))),
                    (Yr+''_comment'', fullcomment)
            ) c (col, val)  
        ) x
        pivot 
        (
           max(val)
           for col in (' + @cols + ')
        ) p '

exec sp_executesql @query;

Vedi SQL Fiddle with Demo . Entrambe le versioni ti daranno il risultato:

| 2015 | 2015_comment | 2014 |                      2014_comment | 2013 |      2013_comment |
|------|--------------|------|-----------------------------------|------|-------------------|
|    1 |       2.13.0 |    2 |  1.16.13 - 2.7.0;  2.8.0 - 2.12.0 |    1 |  1.6.13 - 1.16.13 |

5

Aggiunta di spiegazione e violino: http://sqlfiddle.com/#!6/c92b2/5 .

La seguente query:
1. utilizza una sottoquery per selezionare le versioni min e max per data (min e max vengono applicati agli interi per garantire che, ad esempio, 6 <16)
2. Quindi seleziona l'anno (da raggruppare in seguito), la data (a ordine) e le versioni min - max

SELECT LEFT(UPG_DATE, 4) AS Year
    , UPG_DATE
    , CONVERT(varchar(1), MIN_VER/1000000) + '.' + CONVERT(varchar(2), (MIN_VER/1000 - (MIN_VER/1000000)*1000)) + '.' + CONVERT(varchar(2), MIN_VER%1000)
        + ' - ' + CONVERT(varchar(1), MAX_VER/1000000) + '.' + CONVERT(varchar(2), (MAX_VER/1000 - (MAX_VER/1000000)*1000)) + '.' + CONVERT(varchar(2), MAX_VER%1000) AS Versions
INTO #Versions
FROM (
    SELECT CONVERT(varchar(10), SCHEMA_VER_DATE, 112) as UPG_DATE
        , MIN(SCHEMA_VER_MAJOR*1000000 + SCHEMA_VER_MINOR*1000 + SCHEMA_VER_SUB) AS MIN_VER
        , MAX(SCHEMA_VER_MAJOR*1000000 + SCHEMA_VER_MINOR*1000 + SCHEMA_VER_SUB) AS MAX_VER
    FROM audit_schema_version
    WHERE SCHEMA_VER_REMARK like 'Stored procedure build'
    GROUP BY CONVERT(varchar(10), SCHEMA_VER_DATE, 112)
) Versions;

Successivamente, poiché ogni colonna verrà ripetuta (year e year_COMMENT), vengono selezionate due colonne per identificare i dati. Il numero di date viene conteggiato per conoscere il numero di aggiornamenti e le versioni sono raggruppate per anno, in modo da ottenere tutto in una riga. Questo ci dà il tavolo finale che verrà utilizzato per il pivot.

SELECT Year, Year + '_COMMENT' as Year_COMMENT
    , COUNT(Year) AS Upgrades
    , STUFF((SELECT ' ; ' + SUB.Versions
                FROM #Versions SUB
                WHERE SUB.Year = V.Year
                ORDER BY UPG_DATE ASC
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(2000)')
            ,1,3,'') Versions
INTO #GroupedResults
FROM #Versions V
GROUP BY Year

SELECT * FROM #GroupedResults

Ecco i risultati:

| Year | Year_COMMENT | Upgrades | Versions                         |
|------|--------------|----------|----------------------------------|
| 2013 | 2013_COMMENT | 1        | 1.6.13 - 1.16.13                 |
| 2014 | 2014_COMMENT | 2        | 1.16.13 - 2.7.0 ; 2.8.0 - 2.12.0 |
| 2015 | 2015_COMMENT | 1        | 2.13.0 - 2.13.0                  |

Successivamente, una variabile viene riempita con le colonne, ordinate come vogliamo mostrarle:

DECLARE @cols VARCHAR(1000),
    @finalQuery VARCHAR(2000)

SELECT @cols = STUFF((SELECT ',' + QUOTENAME(YEAR) + ',' + QUOTENAME(YEAR + '_COMMENT')
                    FROM #GroupedResults
                    GROUP BY YEAR
                    ORDER BY YEAR DESC
                    FOR XML PATH(''), TYPE
                    ).value('.', 'NVARCHAR(2000)')
    ,1,1,'')

Infine, la seguente query utilizza cross
Apply in modo da ottenere: 1. La colonna col riempita con i valori Year e Year_COMMENT
2. La colonna del valore riempita con il numero di aggiornamenti, nelle righe corrispondenti agli anni e ai valori delle versioni, nella righe corrispondenti a Year_COMMENTs
Un pivot viene utilizzato sulle due colonne risultanti dandoci i valori (numero di aggiornamenti che si alternano con le versioni) sul col (Anni che si alternano a Year_COMMENTs)

set @finalQuery = N'SELECT ' + @cols + N' from 
             (
                select col, value
                from #GroupedResults
                cross apply
                (
                    SELECT CAST(Upgrades AS VARCHAR(200)), Year
                    UNION ALL
                    SELECT CAST(Versions AS VARCHAR(200)), Year_COMMENT
                ) c (value, col)
            ) x
            pivot 
            (
                Min(value)
                for col in (' + @cols + N')
            ) p1
            ; '

EXEC (@finalQuery);

DROP TABLE #Versions;
DROP TABLE #GroupedResults;

Ciò restituisce i seguenti risultati:

| 2015 | 2015_COMMENT    | 2014 | 2014_COMMENT                     | 2013 | 2013_COMMENT     |
|------|-----------------|------|----------------------------------|------|------------------|
| 1    | 2.13.0 - 2.13.0 | 2    | 1.16.13 - 2.7.0 ; 2.8.0 - 2.12.0 | 1    | 1.6.13 - 1.16.13 |
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.