原始數據:

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;

