Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

MySQL Pivot Query dengan Jumlah nilai kolom

Untuk sql pivot tetap, coba ini:

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

DEMO SQLFiddle DI SINI

Untuk sql pivot dinamis, coba ini:

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;

DEMO SQLFiddle DI SINI




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. MySQL berbeda dihitung jika kondisinya unik

  2. Perilaku MySQL DATEDIFF yang tidak konsisten

  3. Tabel MySQL sebagai FIFO/Antrian

  4. SQL Query untuk mengembalikan maksimum selama beberapa dekade

  5. Bagaimana cara menampilkan statistik kueri basis data di situs Wordpress?