E
E
Express7772016-03-26 18:32:49
Database design
Express777, 2016-03-26 18:32:49

How to convert a vertical table to a horizontal one?

What is there?
There is a table like this

+----+--------------+-------+--------------+
| id | product_name | count | warehouse_id |
+----+--------------+-------+--------------+
|  1 | Puperproduct |    10 |            1 |
|  2 | Puperproduct |    15 |            2 |
|  3 | Puperproduct |    12 |            3 |
+----+--------------+-------+--------------+


What do you need to get?
You need to get the max and min quantity of goods with their warehouses.
+-----+---------------+-----------+------------------+-----------+------------------+
| id  | product_name  | min_count | min_warehouse_id | max_count | max_warehouse_id |
+-----+---------------+-----------+------------------+-----------+------------------+
|  1  | Puperproduct  |        10 |                1 |        15 |                2 |
+-----+---------------+-----------+------------------+-----------+------------------+


What did I get?
Happened:
select 
  id
  , product_name
  , min(count) as min_count
  , max(count) as max_count
from table
group by product_name

+----+--------------+-----------+-----------+
| id | product_name | min_count | max_count |
+----+--------------+-----------+-----------+
|  1 | Puperproduct |        10 |        15 |
+----+--------------+-----------+-----------+


How to get warehouse id? The number of entries is about 800K. MySQL 5.5

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Express777, 2016-04-01
@Express777

Answer to
en.stackoverflow.com/questions/506922/%D0%9A%D0%B0...

D
Dmitry Kovalsky, 2016-03-26
@dmitryKovalskiy

Since there is no PIVOT statement in mysql, there are solutions like this - stackoverflow.com/questions/7674786/mysql-pivot-table

O
Oleg Agapov, 2016-03-27
@oleg_agapov

This is called the groupwise maximum (or minimum, depending on the task).
There is an example here stackoverflow.com/questions/755918/simple-query-to...
Unfortunately, I can't tell you how to implement it in Muskule because I did it only in Oracle (there is a wonderful function row_number()).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question