MySQL single table static and dynamic pivot

MySQLpivot

I have a table that looks like this:

+----------------------------------------+
|Name                | kode      | jum   |
+----------------------------------------+
| aman               |kode1      | 2     |
| aman               |kode2      | 1     |
| jhon               |kode1      | 4     |
| amir               |kode2      | 4     |
+--------------------+-----------+-------+

How can I make a view like this with MySQL?

                    kode1    kode2     count
aman                  2         1        3  
jhon                  0         4        4
amir                  0         4        4

Best Answer

This is a form of a "pivot", you should use that search term to find other options.

You can try something like this:

select
     name
   , sum(case when kode = 'kode1' then jum else 0 end) as 'kode1'
   , sum(case when kode = 'kode2' then jum else 0 end) as 'kode2'
   , sum(jum) as count
from foo
group by name;

(assuming your example view has an error for jhon)

Example:

mysql> select * from foo;
+------+-------+------+
| name | kode  | jum  |
+------+-------+------+
| aman | kode1 |    2 |
| aman | kode2 |    1 |
| jhon | kode1 |    4 |
| amir | kode2 |    4 |
+------+-------+------+
4 rows in set (0.00 sec)


mysql> select
    ->      name
    ->    , sum(case when kode = 'kode1' then jum else 0 end) as 'kode1'
    ->    , sum(case when kode = 'kode2' then jum else 0 end) as 'kode2'
    ->    , sum(jum) as count
    -> from foo
    -> group by name;
+------+-------+-------+-------+
| name | kode1 | kode2 | count |
+------+-------+-------+-------+
| aman |     2 |     1 |     3 |
| amir |     0 |     4 |     4 |
| jhon |     4 |     0 |     4 |
+------+-------+-------+-------+
3 rows in set (0.00 sec)