当前位置: 代码迷 >> PB >> 求一 SQL语句 ,行转列,该如何解决
  详细解决方案

求一 SQL语句 ,行转列,该如何解决

热度:40   发布时间:2016-04-29 08:19:44.0
求一 SQL语句 ,行转列
查询语句:

select c.ZD 诊断,a.LB 费用类别,a.HZJE 费用金额 from SRCXB_ZYBR a,NHBBD b ,CYZMS c 
where a.ZYH=b.ZYH and a.ZYH=c.ZYH 
order by c.ZD,a.LB

结果:
 诊断 费用类别 费用金额
白内障 1 30.00
白内障 1 75.00
白内障 1 90.00
白内障 1 75.00
白内障 1 75.00
白内障 1 75.00
白内障 1 90.00
白内障 1 75.00
白内障 1 75.00
白内障 1 90.00
白内障 1 105.00
白内障 2 12.00
白内障 2 12.00
白内障 2 10.00
白内障 2 10.00
白内障 2 10.00
白内障 2 8.00
白内障 2 8.00
白内障 2 10.00
白内障 2 10.00
白内障 2 10.00
白内障 2 14.00
白内障 3 36.00
白内障 3 122.00
白内障 3 120.00
白内障 3 120.00
白内障 3 38.00
白内障 3 35.00
白内障 3 35.00
白内障 3 37.00
白内障 3 35.00
白内障 3 121.00
白内障 3 120.00
白内障 4 105.50
  …………
膀胱恶性肿瘤 1 30.00
膀胱恶性肿瘤 1 150.00
膀胱恶性肿瘤 1 330.00
膀胱恶性肿瘤 1 60.00
膀胱恶性肿瘤 1 120.00
膀胱恶性肿瘤 2 16.00
膀胱恶性肿瘤 2 16.00
膀胱恶性肿瘤 2 28.00
膀胱恶性肿瘤 2 18.00
膀胱恶性肿瘤 2 4.00
膀胱恶性肿瘤 3 25.00
膀胱恶性肿瘤 3 334.00
膀胱恶性肿瘤 4 152.00
膀胱恶性肿瘤 4 49.00
膀胱恶性肿瘤 4 29.00
膀胱恶性肿瘤 4 29.00
膀胱恶性肿瘤 4 313.50
膀胱恶性肿瘤 5 277.00

要求实现如下:

诊断 类别1金额合计 类别2金额合计 类别3金额合计  
白内障 
膀胱恶性肿瘤

……  



------解决方案--------------------
select 诊断=c.ZD ,
类别1金额合计=sum(case a.LB when 1 then a.HZJE else 0 end),
类别2金额合计=sum(case a.LB when 2 then a.HZJE else 0 end),
类别3金额合计=sum(case a.LB when 3 then a.HZJE else 0 end)
from SRCXB_ZYBR a,NHBBD b ,CYZMS c
where a.ZYH=b.ZYH and a.ZYH=c.ZYH 
group by c.ZD

------解决方案--------------------
http://topic.csdn.net/u/20111009/16/22dee7d1-001e-422a-92cb-66bd14f05e30.html
参考下这个看看
------解决方案--------------------
[code=SQL]
create table emi
(诊断 varchar(16), 费用类别 int, 费用金额 decimal(5,2))

insert into emi
select '白内障 ', 1, 30.00 union all
select '白内障 ', 1, 75.00 union all
select '白内障 ', 1, 90.00 union all
select '白内障 ', 1, 75.00 union all
select '白内障 ', 1, 75.00 union all
select '白内障 ', 1, 75.00 union all
select '白内障 ', 1, 90.00 union all
select '白内障 ', 1, 75.00 union all
select '白内障 ', 1, 75.00 union all
select '白内障 ', 1, 90.00 union all
select '白内障 ', 1, 105.00 union all
select '白内障 ', 2, 12.00 union all
select '白内障 ', 2, 12.00 union all
select '白内障 ', 2, 10.00 union all
select '白内障 ', 2, 10.00 union all
select '白内障 ', 2, 10.00 union all
select '白内障 ', 2, 8.00 union all
select '白内障 ', 2, 8.00 union all
select '白内障 ', 2, 10.00 union all
select '白内障 ', 2, 10.00 union all
select '白内障 ', 2, 10.00 union all
select '白内障 ', 2, 14.00 union all
select '白内障 ', 3, 36.00 union all
select '白内障 ', 3, 122.00 union all
select '白内障 ', 3, 120.00 union all
select '白内障 ', 3, 120.00 union all
select '白内障 ', 3, 38.00 union all
select '白内障 ', 3, 35.00 union all
select '白内障 ', 3, 35.00 union all
select '白内障 ', 3, 37.00 union all
select '白内障 ', 3, 35.00 union all
select '白内障 ', 3, 121.00 union all
select '白内障 ', 3, 120.00 union all
select '白内障 ', 4, 105.50 union all
select '膀胱恶性肿瘤 ', 1, 30.00 union all
select '膀胱恶性肿瘤 ', 1, 150.00 union all
select '膀胱恶性肿瘤 ', 1, 330.00 union all
select '膀胱恶性肿瘤 ', 1, 60.00 union all
select '膀胱恶性肿瘤 ', 1, 120.00 union all
  相关解决方案