mysql按列名获取结果组

oknrviil  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(274)

这个问题在这里已经有答案了

mysql-从行到列(12个答案)
如何在mysql中返回pivot表输出(9个答案)
两年前关门了。
这是我的tbl\U客户:

c_ID    city       type         amount
----    --------   ----------   ------
1       Boston     Medical      1500
2       Miami      Educational  3000
3       Dallas     Scholarship  1000
4       Boston     Scholarship  1500
5       Miami      Medical      3000
6       Boston     Educational  1000
7       Miami      Medical      3000
8       Dallas     Medical      1000

如何获取如下结果:

city          Medical       Educational    Scholarship
-----------   -----------   ------------   -----------
Boston        1500          1000           1500     
Dallas        1000          Null           1000     
Miami         6000          3000           Null
db2dz4w8

db2dz4w81#

SELECT city
    CASE        
     WHEN type = 'Medical' THEN amount END) Medical,  
     WHEN type = 'Educational' THEN amount END) Educational,   
     WHEN type = 'Scholarship' THEN amount END) Scholarship   
FROM tbl_client
GROUP BY city
k2fxgqgv

k2fxgqgv2#

你可以尝试使用条件加重函数 SUMGROUP BY 架构(mysql v5.7)

CREATE TABLE T(
   c_ID int,
   city varchar(50),
   type varchar(50),
   amount int
);

INSERT INTO T VALUES (1,'Boston','Medical',1500);
INSERT INTO T VALUES (2,'Miami','Educational',3000);
INSERT INTO T VALUES (3,'Dallas','Scholarship',1000);
INSERT INTO T VALUES (4,'Boston','Scholarship',1500);
INSERT INTO T VALUES (5,'Miami','Medical',3000);
INSERT INTO T VALUES (6,'Boston','Educational',1000);
INSERT INTO T VALUES (7,'Miami','Medical',3000);
INSERT INTO T VALUES (8,'Dallas','Medical',1000);

查询#1

SELECT city,          
    SUM(CASE WHEN type = 'Medical' THEN amount END) Medical,  
    SUM(CASE WHEN type = 'Educational' THEN amount END) Educational,   
    SUM(CASE WHEN type = 'Scholarship' THEN amount END) Scholarship   
FROM T 
GROUP BY city;

| city   | Medical | Educational | Scholarship |
| ------ | ------- | ----------- | ----------- |
| Boston | 1500    | 1000        | 1500        |
| Dallas | 1000    |             | 1000        |
| Miami  | 6000    | 3000        |             |

db fiddle视图

相关问题