举个简单的例子吧,这样说明比较清晰
主表:一条记录的ABO字段存储一种血型的编码,amount记录数量
[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]
血型维表:
create table bloodtype
(
  id       VARCHAR2(40) not null,
  name     VARCHAR2(200) not null,
  description VARCHAR2(400)
)
主表里的ABO是血型编码,关联血型维表里的id,
现在想要的结果格式是这样的
{orgname,A型血数量,B型血数量,AB型血数量,O型血数量 }
请问维表应如何关联?

解决方案 »

  1.   

    表名写错了,主表改为 blood  吧O(∩_∩)O哈哈~
      

  2.   


    --這個意思?你的第二個表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;
      

  3.   

    嗯,那个表名写错了⊙﹏⊙b汗
    在3楼的sql里,维表其实没有起到作用,如果那样的话,直接在decode里面写判断类型编码就可以了;
    我是想的能不能在SQL里对维表进行一次遍历性质的,比如维表里面的某个值更改了,不会受影响,不知道这个该怎么搞、、、
      

  4.   


    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                     
      

  5.   


    --4楼很精彩,这个属性以前看过却从没用过,试了下挺好,就是有一点:
    pivot (sum(amount) for abo in ('A','B','AB','O'));
    --in()里面不能写成in(select id from bloodtype)
    --还是需要写死in('A','AB','B','O')
    不知道这个有没有办法解决?
      

  6.   

    还有一点:用pivot的话 ,后面怎么出合计的那一列啊??