MYSQL dynamic crosstab question
Newbie here.
I'm using codeigniter and mysql How can I dynamically (number of names may change) convert table from:
+-开发者_高级运维-----+-------+-------+
| date | name | value |
+------+-------+-------+
| 06-01| A | 1 |
| 06-02| A | 2 |
| 06-02| B | 3 |
| 06-03| C | 4 |
+------+-------+-------+
To:
+------+---+---+---+
| date | A | B | C |
+------|---+---+---|
| 06-01| 1 | | |
| 06-02| 2 | 3 | |
| 06-03| | | 4 |
+------+---+---+---+
?
Thank you.
Something like this should work.
SELECT date,
SUM(IF(name='A',value,0)) AS 'A',
SUM(IF(name='B',value,0)) AS 'B',
SUM(IF(name='C',value,0)) AS 'C'
FROM myTable
GROUP BY date
ORDER BY date
You need to know what your column names could be to add each of the SUMs manually into your SQL statement, but you could do this using PHP if it was likely to change a lot.
Likewise, replace value
with 1
if you just wanted a count of how many times each name appeared, rather than the total of the values in name
.
精彩评论