Query PIVOT or SUM

Asked

Viewed 98 times

0

My consultation is as follows::

 mysql> select product_id, presentation, price from Variant where product_id = "1604";
  +------------+-------------------------+-------+
  | product_id | presentation            | price |
  +------------+-------------------------+-------+
  |       1604 | Unitário = R$ 11,90     |  11.9 |
  |       1604 | 5 Peças = R$ 5,00 cada  |    25 |
  |       1604 | Bluesky Todas           |    15 |
  +------------+-------------------------+-------+
   3 rows in set (0,00 sec)

How would I separate these 3 results for the same 1604 ID into separate columns in SQL?

Example: presentation1, presentation2, presentation3 column-separated

1 answer

1

Simulate the Pivot dynamically

Mysql does not have Pivot. In that case you have two options.

  • Generate a column for each case in one SUM with CASE.
  • Dynamically generate the same SQL if the column content is dynamic.

In the static case, it would be something like:

select product_id,
  sum(case when presentation = 'Unitário = R$ 11,90 ' THEN price END) presentation1,
  sum(case when presentation = '5 Peças = R$ 5,00 cada' THEN price END) presentation2,
  sum(case when presentation = 'Bluesky Todas' THEN price END) presentation3
from product
where product_id = 1604

In the dynamic case, it would look something like:

SET @sql = NULL;
SET @rowid = 0;

SELECT
    GROUP_CONCAT(
    CONCAT(
    'sum(case when presentation = ''',
      presentation,
      ''' then price end) AS ',
      'presentation',
      @rowid := @rowid + 1 
    )
  ) INTO @sql 
FROM 
(SELECT presentation 
 FROM product
 GROUP BY presentation
) AS p;

SET @sql = CONCAT(
  'SELECT product_id, ', 
  @sql, 
  ' from product where product_id = 1604'
);

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

I added the dynamic query to this Fiddle to see working with more records.

  • in the dynamic form returned an error: #1064 - You have a syntax error in your SQL next to ''009- Zener 0,5W from product Where product_id = 1604' in line 1

  • In the static case how would be without putting the names 'Unit = R $ 11,90 ' ?

  • Try running the example from Fiddle. If you have changed the data or have some different character in your table may be influencing the execution.

  • About not putting names, only if you have a table whose names have an associated code. In this case you can do a JOIN and use the code related to the description instead of the description.

  • could you give me an example ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.