测试数据:
--创建表:
create table DRUG_DETAILS
(
drug_name VARCHAR2(10),
drug_id VARCHAR2(10),
price NUMBER(8,2),
pat_id VARCHAR2(10)
)
--插入测试数据:
INSERT INTO drug_details VALUES('阿莫西林','1',10.2);
INSERT INTO drug_details VALUES('枇杷膏','2',8.3);
INSERT INTO drug_details VALUES('感康','3',9.2);
INSERT INTO drug_details VALUES('生理盐水','4',1);
INSERT INTO drug_details VALUES('葡萄糖','5',2);
INSERT INTO drug_details VALUES('酒精','6',7.6);
数据预览:
目标:
--SQL参考一 行转列 关键函数:decode
SELECT
t.pat_id
,SUM(DECODE(t.drug_name,'阿莫西林',t.price)) AS 阿莫西林
,SUM(DECODE(t.drug_name,'枇杷膏',t.price)) AS 枇杷膏
,SUM(DECODE(t.drug_name,'感康',t.price)) AS 感康
,SUM(DECODE(t.drug_name,'生理盐水',t.price)) AS 生理盐水
,SUM(DECODE(t.drug_name,'葡萄糖',t.price)) AS 葡萄糖
,SUM(DECODE(t.drug_name,'酒精',t.price)) AS 酒精
FROM drug_details t
GROUP BY t.pat_id
--SQL参考二 行转列 关键函数:PIVOT
SELECT *
FROM (SELECT pat_id,drug_name,price FROM drug_details) PIVOT (
SUM(price) FOR drug_name IN ('阿莫西林' AS 阿莫西林,'枇杷膏' AS 枇杷膏,'感康' AS 感康,'生理盐水' AS 生理盐水,'酒精' AS 酒精,'葡萄糖' AS 葡萄糖)
)
以上两种方式需要穷举列名,存在限制。可以考虑聚合列的方式,对聚合数据代码中解析:
--SQL参考三 行转列 将结果聚合,代码或脚本中二次拆分
--关键函数 listagg
SELECT t.pat_id,listagg(drug_name||'#'||price,'$') WITHIN GROUP(ORDER BY 1) AS lob_str
FROM drug_details t GROUP BY t.pat_id
效果: