sql >> Base de Datos >  >> RDS >> Mysql

MySQL Pivot Query con la suma del valor de la columna

Para el sql de pivote fijo, intente esto:

select
    t.client_name,
    sum(if(t.distributor = 'Dis A', t.amount, 0)) as `Dis A`,
    sum(if(t.distributor = 'Dis B', t.amount, 0)) as `Dis B`,
    sum(if(t.distributor = 'Dis C', t.amount, 0)) as `Dis C`,
    sum(if(t.distributor = 'Dis D', t.amount, 0)) as `Dis D`
from (
    select c.id, c.client_name, d.distributor, r.amount
    from clients c
    left join reports r on c.id = r.clientId
    left join distributor d on d.id = r.distributorId
)t
group by t.id
order by t.client_name

DEMOSTRACIÓN DE SQLFiddle AQUÍ

Para el sql de pivote dinámico, intente esto:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(if(t.distributor = ''',
      distributor,
      ''', t.amount, 0)) AS `',
      distributor ,'`'
    )
  ) INTO @sql
FROM distributor;
SET @sql = CONCAT('SELECT t.client_name, ', @sql, ' FROM (
    select c.id, c.client_name, d.distributor, r.amount
    from clients c
    left join reports r on c.id = r.clientId
    left join distributor d on d.id = r.distributorId
)t
group by t.id
order by t.client_name');

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

DEMOSTRACIÓN DE SQLFiddle AQUÍ