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

mysql pivottabel dato (lodret til vandret data)

For at få dette resultat, skal du pivotere dataene. MySQL har ikke en pivotfunktion, men du kan bruge en aggregeret funktion med en CASE udtryk.

Hvis antallet af datoer er kendt, kan du hardkode forespørgslen:

select client_id,
  max(case when rownum = 1 then date end) Date1,
  max(case when rownum = 2 then date end) Date2,
  max(case when rownum = 3 then date end) Date3
from
(
  select client_id,
    date,
    @row:=if(@prev=client_id, @row,0) + 1 as rownum,
    @prev:=client_id 
  from yourtable, (SELECT @row:=0, @prev:=null) r
  order by client_id, date
) s
group by client_id
order by client_id, date
 

Se SQL Fiddle with Demo

Jeg implementerede brugervariable for at tildele et rækkenummer til hver post i client_id gruppe.

Hvis du har et ukendt antal datoer, skal du bruge en forberedt erklæring til at oprette sql dynamisk:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN rownum = ',
      rownum,
      ' THEN date END) AS Date_',
      rownum
    )
  ) INTO @sql
from
(
  select client_id,
    date,
    @row:=if(@prev=client_id, @row,0) + 1 as rownum,
    @prev:=client_id 
  from yourtable, (SELECT @row:=0) r
  order by client_id, date
) s
order by client_id, date;


SET @sql 
  = CONCAT('SELECT client_id, ', @sql, ' 
           from
           (
             select client_id,
               date,
               @row:=if(@prev=client_id, @row,0) + 1 as rownum,
               @prev:=client_id 
             from yourtable, (SELECT @row:=0) r
             order by client_id, date
           ) s
           group by client_id
           order by client_id, date');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
 

Se SQL Fiddle with Demo .

De giver begge resultatet:

| CLIENT_ID | DATE_1 | DATE_2 | DATE_3 | -------------------------------------------------------------------------------------------------------------- | 1 | February, 03 2013 00:00:00+0000 | February, 10 2013 00:00:00+0000 | May, 12 2013 00:00:00+0000 | | 2 | February, 03 2013 00:00:00+0000 | July, 15 2013 00:00:00+0000 | (null) |


  1. Hvordan bruger man % operator fra udvidelsen pg_trgm?

  2. mysqli flere forespørgsler - sæt variabel producerer boolesk fejl/hvordan springer man dette over?

  3. Kontrol af Oracle RAC-netværk og IP-oplysninger

  4. PDO og binding af flere værdisæt under indsættelse - for nylig