group rows into columns with sum [duplicate]

这一生的挚爱 提交于 2019-12-13 03:44:29

问题


Let say we have this table:

CREATE TABLE `table1` (
`Name` CHAR(50) NOT NULL,
`Type` CHAR(50) NOT NULL,
`Value` DOUBLE NOT NULL
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;


 ---------------------------------
|   Name   |   Type   |   Value   | 
 ---------------------------------   
|   Dep1   |   Cash   |   100     | 
 ---------------------------------  
|   Dep1   |   Card   |   200     | 
 ---------------------------------  
|   Dep2   |   Cash   |   300     | 
 ---------------------------------  
|   Dep2   |   Card   |   400     | 
 ---------------------------------

How to create a MySQL select query to transform rows in columns like this? I must mention that column 'Name' has dynamic values!

 --------------------------------
|   Name   |   Cash   |   Card   |    
 --------------------------------   
|   Dep1   |    100   |    200   |     
 --------------------------------   
|   Dep2   |    300   |    400   |
 --------------------------------  

回答1:


select name, 
       sum(case when `type` = 'Cash' then `value` else 0 end) as Cash,
       sum(case when `type` = 'Card' then `value` else 0 end) as Card
from your_table
group by name


来源:https://stackoverflow.com/questions/36515502/group-rows-into-columns-with-sum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!