oracle - mysql如何将group by的行数据转为列
PHP中文网
PHP中文网 2017-04-17 16:22:04
0
6
618

原始数据表如下

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列,是否存在效率的瓶颈

PHP中文网
PHP中文网

认证0级讲师

reply all(6)
巴扎黑

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.

刘奇
create table tt1(id int ,name VARCHAR(100),money FLOAT,time DATETIME)
insert into tt1
select 1,'mike',6,'2016-09-01 12:58:00' UNION
select 2,'mike',10,'2016-09-01 13:52:56' UNION
select 3,'leo',10,'2016-09-02 00:05:05' UNION
select 4,'mike',6,'2016-09-03 08:06:05'

select name,sum(case when datediff(time,'2016-09-01')=0 then money else 0 end) as '2016-09-01'
      ,sum(case when datediff(time,'2016-09-02')=0 then money else 0 end) as '2016-09-02'
      ,sum(case when datediff(time,'2016-09-03')=0 then money else 0 end) as '2016-09-03'
from tt1 GROUP BY  name
黄舟

@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

select "select name," 
union 
select concat("sum(case when datediff(time,'",date(time),"')=0 then money else 0 end) as '",date(time),"',") a from tt1 group by a 
union 
select " from tt1 group by name;";

PS:union中间段最后一个逗号记得去掉
伊谢尔伦
SELECT 
    name, 
    sum( if(date_format(time,'%Y-%m-%d') = '2016-09-01', money, 0 ) ) AS '2016-09-01',  
    sum( if(date_format(time,'%Y-%m-%d') = '2016-09-02', money, 0 ) ) AS '2016-09-02',  
    sum( if(date_format(time,'%Y-%m-%d') = '2016-09-03', money, 0 ) ) AS '2016-09-03'
FROM 
    money_table 
GROUP BY 
    name;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template