sql >> Database teknologi >  >> RDS >> Mysql

Hvordan man pivoterer tabeller i MySQL

Der er 3 ting at tænke over 1) Hvordan man dynamisk genererer en masse max(case when 2) at tildele noget til at gruppere sagen når's by - i dette tilfælde genererer jeg et rækkenummer ved hjælp af en variabel 3) nogle af dine jobtitler indeholder hvidt mellemrum, som jeg fjerner for generering af kolonneoverskrifter

set @sql = 
            (select concat('select ', gc,            ' from 
             (select name,job_title,
                if (job_title <> @p, @rn:=1 ,@rn:[email protected]+1) rn,
                @p:=job_title p
                from t
                cross join (select @rn:=0,@p:=null) r
                order by job_title
              ) s group by rn;') from
            (select 
                group_concat('max(case when job_title = ', char(39),job_title ,char(39),' then name else char(32) end ) as ',replace(job_title,char(32),'')) gc
                from
                (
                select distinct job_title from t
                ) s
                ) t
             )
;           
 

Genererer denne sql-kode

select max(case when job_title = 'Fireman' then name else char(32) end ) as Fireman,
        max(case when job_title = 'Driver' then name else char(32) end ) as Driver,
        max(case when job_title = 'Analyst' then name else char(32) end ) as Analyst,
        max(case when job_title = 'Postman' then name else char(32) end ) as Postman,
        max(case when job_title = 'Research Manager' then name else char(32) end ) as ResearchManager
         from 
             (select name,job_title,
                if (job_title <> @p, @rn:=1 ,@rn:[email protected]+1) rn,
                @p:=job_title p
                from t
                cross join (select @rn:=0,@p:=null) r
                order by job_title
              ) s group by rn;
 

Som kan indsendes til dynamisk sql

prepare sqlstmt from @sql;
execute sqlstmt;
deallocate prepare sqlstmt;
 

resultat

+---------+--------+---------+---------+-----------------+ | Fireman | Driver | Analyst | Postman | ResearchManager | +---------+--------+---------+---------+-----------------+ | Sam | Tomas | Lisa | Marcus | Mary | | Peter | Chen | Stephan | | | | | | Albert | | | +---------+--------+---------+---------+-----------------+ 3 rows in set (0.00 sec)

  1. Brug SET TEXTSIZE til at begrænse de data, der returneres for hver række i SQL Server

  2. Optimal forespørgsel til at hente en kumulativ sum i MySQL

  3. Hvordan gemmer man dato-tid i UTC i en database ved hjælp af EclipseLink og Joda-Time?

  4. Pivot med flere kolonner i T-SQL