mysql按列名获取结果组

时间:2018-12-09 07:13:54

标签: mysql sql

这是我的tbl_client:

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

2 个答案:

答案 0 :(得分:0)

您可以尝试将条件加重函数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        |             |

View on DB Fiddle

答案 1 :(得分:0)

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