信息表A 项目表 B
id, id,
name, A.id,
age, 项目名称
sex姓名 年龄 性别 项目1 项目2 项目3
张三 16 男 X1 NULL NULL
张三 16 男 NULL X2 NULL
张三 16 男 NULL NULL X3现在查询出来的结果是这种,如果去掉在一行结果中显示出来,不要分成三行。SQL分组查询
id, id,
name, A.id,
age, 项目名称
sex姓名 年龄 性别 项目1 项目2 项目3
张三 16 男 X1 NULL NULL
张三 16 男 NULL X2 NULL
张三 16 男 NULL NULL X3现在查询出来的结果是这种,如果去掉在一行结果中显示出来,不要分成三行。SQL分组查询
go
create table [TB] (姓名 nvarchar(4),年龄 int,性别 nvarchar(2),项目1 nvarchar(4),项目2 nvarchar(4),项目3 nvarchar(4))
insert into [TB]
select '张三',16,'男','X1',null,null union all
select '张三',16,'男',null,'X2',null union all
select '张三',16,'男',null,null,'X3'select 姓名,年龄,性别,max(项目1 ) as 项目1 ,max(项目2 ) as 项目2,max(项目3 ) as 项目3
from TB
group by 姓名,年龄,性别/*
姓名 年龄 性别 项目1 项目2 项目3
张三 16 男 X1 X2 X3*/
张三 16 男 X1 X2 X3
case b.genderno when 1 then '男'
when 2 then '女' end as '性别',b.age as '年龄',b.formmemo as '体检号',
(select c.reportvalue from reportitem c where c.itemno=50002 and c.formno=a.formno and a.itemno=c.itemno) as '项目1',
(select c.reportvalue from reportitem c where c.itemno=50004 and c.formno=a.formno and a.itemno=c.itemno) as '项目2',
(select c.reportvalue from reportitem c where c.itemno=50032 and c.formno=a.formno and a.itemno=c.itemno) as '项目3'
from reportitem a
inner join reportform b on a.formno=b.formno and b.clientno=322 and b.sicktypeno=3 and b.formstateno=3 and receivedate >='2013-06-13' and receivedate <='2013-06-13'
inner join testitem c on a.itemno=c.itemno
order by b.cname
目前结果为
姓名 年龄 性别 项目1 项目2 项目3
张三 16 男 X1 NULL NULL
张三 16 男 NULL X2 NULL
张三 16 男 NULL NULL X3
select b.cname as '姓名',
case b.genderno when 1 then '男'
when 2 then '女' end as '性别',b.age as '年龄',b.formmemo as '体检号',
(select c.reportvalue from reportitem c where c.itemno=50002 and c.formno=a.formno and a.itemno=c.itemno) as '项目1',
(select c.reportvalue from reportitem c where c.itemno=50004 and c.formno=a.formno and a.itemno=c.itemno) as '项目2',
(select c.reportvalue from reportitem c where c.itemno=50032 and c.formno=a.formno and a.itemno=c.itemno) as '项目3'
from reportitem a
inner join reportform b on a.formno=b.formno and b.clientno=322 and b.sicktypeno=3 and b.formstateno=3 and receivedate >='2013-06-13' and receivedate <='2013-06-13'
inner join testitem c on a.itemno=c.itemno
group by b.cname,b.genderno,b.age,b.formmemo
order by b.cname试试
得出的结果依然是:
姓名 年龄 性别 项目1 项目2 项目3
张三 16 男 X1 NULL NULL
张三 16 男 NULL X2 NULL
张三 16 男 NULL NULL X3
from(
select * from B
) as C
pivot
(
max(项目名称) for id in (1,2,3)
) as pvt
1,2,3代表项目的id,最后用这个结果去和人员信息表关联就行了