Mysql
 sql >> Datenbank >  >> RDS >> Mysql

MySQL-Pivot-Abfrage mit Summe des Spaltenwerts

Versuchen Sie für die feste Pivot-SQL Folgendes:

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

SQLFiddle-DEMO HIER

Versuchen Sie für das dynamische Pivot-SQL Folgendes:

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;

SQLFiddle-DEMO HIER