日期:2014-05-17  浏览次数:20934 次

Oracle里分类统计的问题
举个简单的例子吧,这样说明比较清晰
主表:一条记录的ABO字段存储一种血型的编码,amount记录数量
SQL code
[code=SQL]create table bloodtype
(
  id          VARCHAR2(40) not null,
  orgcode     VARCHAR2(200) not null,
  orgname     VARCHAR2(200) not null,
  ABO         VARCHAR2(40) not null,
  amount      VARCHAR2(20),
  creatdate   VARCHAR2(400)
)
[/code]
血型维表:
SQL code
create table bloodtype
(
  id       VARCHAR2(40) not null,
  name     VARCHAR2(200) not null,
  description VARCHAR2(400)
)

主表里的ABO是血型编码,关联血型维表里的id,
现在想要的结果格式是这样的
{orgname,A型血数量,B型血数量,AB型血数量,O型血数量 }
请问维表应如何关联?

------解决方案--------------------
SQL code

--這個意思?你的第二個表bloodtype寫錯了吧,我用bloodtypedtl代替的,值就用A,B,AB,O代替的
select 
    bloodtype.orgname,    
    sum(decode(bloodtypedtl.name,'A',bloodtype.amount,0)) "A型血数量",
    sum(decode(bloodtypedtl.name,'B',bloodtype.amount,0)) "B型血数量",
    sum(decode(bloodtypedtl.name,'AB',bloodtype.amount,0)) "AB型血数量",
    sum(decode(bloodtypedtl.name,'O',bloodtype.amount,0)) "O型血数量"
from bloodtype,bloodtypedtl
where bloodtype.ABO=bloodtypedtl.id
group by bloodtype.orgname;

------解决方案--------------------

with t as (
select '001' as code, 'A' as abo,12 as amount from dual
union all
select '001','B',22 from dual
union all
select '001','AB',32 from dual
union all
select '001','O',21 from dual
union all
select '002','B',45 from dual
union all
select '002','AB',54 from dual
union all
select '002','O',44 from dual
union all
select '002','A',55 from dual
)
select * from t
pivot (sum(amount) for abo in ('A','B','AB','O'));
CODE 'A' 'B' 'AB' 'O'
---- ---------------------- ---------------------- ---------------------- ---------------------- 
002 55 45 54 44
001 12 22 32 21