Is it possible to use Crosstab / Pivot Query in MySQL?

I am using MySQL. This is the table in which I

supplier_ID Item_ID Date Price QTY 1 1 2012-01-01 00:00:00 500.00 2 1 1 2012-01-03 00:00:00 450.00 10 2 1 2012-01-01 00:00:00 400.00 5 3 1 2012-05-01 00:00:00 500.00 1 

I need a select query showing a table something like this.

 supplier_ID 2012-01-01 2012-01-03 2012-05-01 1 500.00(2) 450.00(10) null 2 400.00(5) null null 3 null null 500.00(1) 
+6
source share
2 answers

You can use this query -

 SELECT supplier_id, MAX(IF(date = '2012-01-01', value, NULL)) AS '2012-01-01', MAX(IF(date = '2012-01-03', value, NULL)) AS '2012-01-03', MAX(IF(date = '2012-05-01', value, NULL)) AS '2012-05-01' FROM ( SELECT supplier_id, DATE(date) date, CONCAT(SUM(price), '(', qty, ')') value FROM supplier GROUP BY supplier_id, DATE(date) ) t GROUP BY supplier_id; +-------------+------------+------------+------------+ | supplier_id | 2012-01-01 | 2012-01-03 | 2012-05-01 | +-------------+------------+------------+------------+ | 1 | 500.00(2) | 450.00(10) | NULL | | 2 | 400.00(5) | NULL | NULL | | 3 | NULL | NULL | 500.00(1) | +-------------+------------+------------+------------+ 

It produces the result you want. But if you want to do this dynamically, check out this article, “Automate PivotTables” - http://www.artfulsoftware.com/infotree/queries.php#523 , or this link - Dynamic Pivot Tables .

+6
source
 SELECT supplier_ID, CONCAT(SUM(IF(`date`='2012-01-01',ROUND(Price,2),NULL)), '(', SUM(IF(`date`='2012-01-01',QTY,NULL)), ')') AS '2012-01-01', CONCAT(SUM(IF(`date`='2012-01-03',ROUND(Price,2),NULL)), '(', SUM(IF(`date`='2012-01-03',QTY,NULL)), ')') AS '2012-01-03', CONCAT(SUM(IF(`date`='2012-05-01',ROUND(Price,2),NULL)), '(', SUM(IF(`date`='2012-05-01',QTY,NULL)), ')') AS '2012-05-01' FROM supplier GROUP BY supplier_ID 
0
source

Source: https://habr.com/ru/post/906363/


All Articles