举个简单的例子吧,这样说明比较清晰
主表:一条记录的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型血数量 }
请问维表应如何关联?
主表:一条记录的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型血数量 }
请问维表应如何关联?
解决方案 »
- 出现非单组函数的错误 求大师讲解
- merge into 求助
- 请教一个commit=y及INI文件里参数的问题?
- 关于ExecuteNonQuery 调用存储过程返回受影响行数的问题
- oracle92和ghost冲突,请高手指点
- 菜鳥問題﹕一個procedure 大家幫幫忙呀
- 一用户使用truncate table命令删除了一个重要的业务记录表内容,数据库设置为Noarchievelog,且没有备份。愿出1000元人民币,有效期7天。
- csdn 怎么老是服务器繁忙?现在都夜间快四点了,竟然还是这样!
- insert 语句怎么用啊 我要在表中加一个账号
- 动态语句 983 错误,求解
- distinct 和 group by 在查询多列数据去重复时的区别在哪?
- 求一UPDATE语句
--這個意思?你的第二個表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楼的sql里,维表其实没有起到作用,如果那样的话,直接在decode里面写判断类型编码就可以了;
我是想的能不能在SQL里对维表进行一次遍历性质的,比如维表里面的某个值更改了,不会受影响,不知道这个该怎么搞、、、
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
--4楼很精彩,这个属性以前看过却从没用过,试了下挺好,就是有一点:
pivot (sum(amount) for abo in ('A','B','AB','O'));
--in()里面不能写成in(select id from bloodtype)
--还是需要写死in('A','AB','B','O')
不知道这个有没有办法解决?