patternsqlModerate
MySQL single table static and dynamic pivot
Viewed 0 times
pivotmysqlsingledynamicandtablestatic
Problem
I have a table that looks like this:
How can I make a view like this with MySQL?
+----------------------------------------+
|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 4Solution
If you have a known number of columns, then you can use a static version similar to the other answer. But if you have an unknown number then you can use a prepared statement similar to this:
See SQL Fiddle with demo
Result is the same:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when kode = ''',
kode,
''' then jum else 0 end) AS ',
kode
)
) INTO @sql
FROM yourtable;
SET @sql = CONCAT('SELECT name, ', @sql, ', sum(jum) as `count`
FROM yourtable
GROUP BY name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;See SQL Fiddle with demo
Result is the same:
| NAME | KODE1 | KODE2 | COUNT |
--------------------------------
| aman | 2 | 1 | 3 |
| amir | 0 | 4 | 4 |
| jhon | 4 | 0 | 4 |Code Snippets
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when kode = ''',
kode,
''' then jum else 0 end) AS ',
kode
)
) INTO @sql
FROM yourtable;
SET @sql = CONCAT('SELECT name, ', @sql, ', sum(jum) as `count`
FROM yourtable
GROUP BY name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;| NAME | KODE1 | KODE2 | COUNT |
--------------------------------
| aman | 2 | 1 | 3 |
| amir | 0 | 4 | 4 |
| jhon | 4 | 0 | 4 |Context
StackExchange Database Administrators Q#27659, answer score: 11
Revisions (0)
No revisions yet.