I tried searching for posts but only found solutions for SQL Server/Access. I need a solution in MySQL (5.X).
I have a table (called history) with 3 columns: hostid, itemname, itemvalue.
If I do a select (select * from History
) it returns
+--------+----------+-----------+ | hostid | itemname | itemvalue | +--------+----------+-----------+ | 1 | A | 10 | +--------+----------+-----------+ | 1 | B | 3 | +--------+----------+-----------+ | 2 | A | 9 | +--------+----------+-----------+ | 2 | C | 40 | +--------+----------+-----------+
How to query the database to return similar content
+--------+------+-----+-----+ | hostid | A | B | C | +--------+------+-----+-----+ | 1 | 10 | 3 | 0 | +--------+------+-----+-----+ | 2 | 9 | 0 | 40 | +--------+------+-----+-----+
I will add a longer, more detailed description of the steps to resolve this issue. I apologize if it's too long.
I'll start with the foundation you gave and use it to define a few terms that I will use throughout the rest of this article. This will be base table:
This will be our goal, Beautiful pivot table:
The value in thehistory.hostid
column will become the y value in the pivot table. The values in thehistory.itemname
column will become x-values (for obvious reasons).When I have to solve the problem of creating a pivot table, I use a three-step process to solve it (with an optional fourth step):
. In the desired result, hostid provides the
Step 2: Extend the base tabley value
and itemname provides thex value
.with additional columns. We usually want one column for each x value. Recall that our x-value column is itemname:
Note that we did not change the number of rows - we just added extra columns. Also note the pattern of
NULL- the row with
Step 3: Group and aggregate the extended tableitemname = "A"
has a non-null value for the new columnA
, and the other new column has a null value.. We need grouping by hostid since it provides the y value:
(Note that we now have one row per y value.)Okay, we're almost there! We just need to get rid of those ugly NULL.
Step 4: Beautify. We will replace any null values with zeros so that the result set looks better:
We’re done – we’ve built a beautiful pivot table using MySQL.itemvalue-
NULL- , but it could also be
What aggregate function to use when grouping. I used sum- , but
Use multiple columns to represent y values. This solution is not limited to using a single column for the y values - just insert the extra columns into the group by- clause (and don't forget to
Known limitations:
in this example
What "neutral" values to use in extra columns. I used0
or""
, depending on your situationcount
andmax
are also often used (max
is often used when building a single row) spread across multiple rows Object")select
them)