原始数据:
DROP TABLE IF EXISTS medical_info;
CREATE TABLE medical_info(
id INT PRIMARY KEY not NULL auto_increment,
bm VARCHAR(32) DEFAULT '急诊科',
lxmc VARCHAR(20),
lx VARCHAR(10),
sl INT,
je DECIMAL(5,2)
);
INSERT INTO medical_info(lxmc,lx,sl,je)
VALUES('检查','05',7,480.00),('放射','07',3,140.00),('成药','02',1,198.00),('西药','01',3,106.48),('治疗','04',20,46.00),('化验','06',3,15.00);
SELECT * from medical_info;
-- 将一行数据转换为一列进行显示,同时匹配不到的时候,价格默认为0
转换后:
SELECT
bm,
SUM(CASE
WHEN lxmc = '西药' THEN je
END )AS '西药',
SUM(CASE
WHEN lxmc = '成药' THEN je
END )AS'成药',
SUM(CASE
WHEN lxmc = '草药' THEN je --草药是图中je(金额)为0的一项,所以图中没显示出来,但想在最后的结果中显示
ELSE 0 END )AS'草药',
SUM(CASE
WHEN lxmc = '治疗' THEN je
END )AS '治疗',
SUM(CASE
WHEN lxmc = '检查' THEN je
END )AS '检查',
SUM(CASE
WHEN lxmc = '化验' THEN je
END )AS '化验',
SUM(CASE
WHEN lxmc = '放射' THEN je
END )AS '放射'
FROM medical_info;