原始数据表如下
id | name | money | time |
---|---|---|---|
1 | mike | 6 | 2016-09-01 12:58:00 |
2 | mike | 10 | 2016-09-01 13:52:56 |
3 | leo | 10 | 2016-09-02 00:05:05 |
4 | mike | 6 | 2016-09-03 08:06:05 |
希望转制后的数据表如下
name | 2016-09-01 | 2016-09-02 | 2016-09-03 |
---|---|---|---|
mike | 16 | 0 | 6 |
leo | 0 | 10 | 0 |
以demo为例,可以说说这类问题的解决思路吗?比如统计两个月的数据,那么就会有60行转为60列,是否存在效率的瓶颈
select sum(money) s,name,date_format(time,'%Y-%m-%d') d from table group by name,d;
Then convert according to here
If you have to use SQL, you have to write a stored procedure and then create a temporary table.
No need, just take out the data and use the server to do it. Much more efficient.
@ch21st gave you a typical row-to-column SQL writing method
Because the table only needs to be scanned once, there is generally no performance problem unless it is a particularly large table.
This writing method itself is just a solution idea. If the columns are not fixed, the sql statement can be dynamically generated through php or java on the application side.
Just write the sql that generates the script and you’re done