我在医疗数据库中有3个表,
表:成员
id_member name
1 Pendi
2 Ardi
3 Hafiz
4 Arista
表:好处
id_member id_benefit year
1 1 2016
1 2 2016
1 3 2016
2 4 2016
2 5 2016
2 6 2016
3 7 2016
3 8 2016
3 9 2016
4 10 2016
4 11 2016
4 12 2016
表:masterbenefit
id_masterbenefit benefit_name benefit_value
1 inpatient 100000
2 outpatient 2000
3 dental 300
4 inpatient 150000
5 outpatient 2500
6 dental 350
7 inpatient 170000
8 outpatient 2750
9 dental 375
10 inpatient 190000
11 outpatient 2900
12 dental 390
我想在一个表格中显示
No. Member-Name Year Inpatient Outpatient Dental
1. Pendi 2016 100000 2000 300
2. Ardi 2016 150000 2500 350
3. Hafiz 2016 170000 2750 375
4. Arista 2016 190000 2900 390
我有这样的查询(来自本网站的其他问题),但这不是我需要的。
SELECT A.name NAME,
CASE WHEN B.id_benefit='1' THEN C.benefit_value END Inpatient,
CASE WHEN B.id_benefit='2' THEN C.benefit_value END Outpatient,
CASE WHEN B.id_benefit='3' THEN C.benefit_value END Dental,
CASE WHEN B.id_benefit='4' THEN C.benefit_value END Inpatient,
CASE WHEN B.id_benefit='5' THEN C.benefit_value END Outpatient,
CASE WHEN B.id_benefit='6' THEN C.benefit_value END Dental,
CASE WHEN B.id_benefit='7' THEN C.benefit_value END Inpatient,
CASE WHEN B.id_benefit='8' THEN C.benefit_value END Outpatient,
CASE WHEN B.id_benefit='9' THEN C.benefit_value END Dental,
CASE WHEN B.id_benefit='10' THEN C.benefit_value END Inpatient,
CASE WHEN B.id_benefit='11' THEN C.benefit_value END Outpatient,
CASE WHEN B.id_benefit='12' THEN C.benefit_value END Dental,
FROM member A, benefit B, masterbenefit C
WHERE A.id_member=B.id_member
AND B.id_benefit=C.id_masterbenefit
GROUP BY A.id_member
ORDER BY A.name
答案 0 :(得分:0)
使用Joins
组合数据和group by
为每个成员分组数据:
试试这个:
select
@row_num:=@row_num+1 as no,
m.name,
b.year,
max(if(mb.benefit_name='inpatient',mb.benefit_value,0)) as inpatient,
max(if(mb.benefit_name='outpatient',mb.benefit_value,0)) as outpatient,
max(if(mb.benefit_name='dental',mb.benefit_value,0)) as dental
from member m
inner join benefit b on m.id_member=b.id_member
inner join masterbenefit mb on b.id_benefit=mb.id_masterbenefit,(select @row_num:=0) as p
group by m.id_member,b.year