对不起,我没有拿出一个好问题的标题,所以随意相应地改变它。在一列中聚合不同的行SQL查询
我可以描述我的问题在MS SQL Server 2012的一个小例子:
create table #tmp
(
RowID varchar(10),
SectionCode int,
SectionName varchar(10)
)
insert into #tmp values('Record1' , 1 , 'AB');
insert into #tmp values('Record1' , 2 , 'CD');
insert into #tmp values('Record1' , 3 , 'EF');
insert into #tmp values('Record2' , 1 , 'AB');
insert into #tmp values('Record2' , 4 , 'GH');
insert into #tmp values('Record2' , 5 , 'IJ');
insert into #tmp values('Record3' , 2 , 'CD');
insert into #tmp values('Record3' , 5 , 'IJ');
我想创建每个记录结果的一排,其中每个部分是一列,如果有一个排与一个部分相关联,相应的列值增加。这是(不)我想要的东西(在不同的行相同的记录数据)
select RowID,
case when SectionName = 'AB' then 1 else 0 end as [AB Section] ,
case when SectionName = 'CD' then 1 else 0 end as [CD Section] ,
case when SectionName = 'EF' then 1 else 0 end as [EF Section] ,
case when SectionName = 'GH' then 1 else 0 end as [GH Section] ,
case when SectionName = 'IJ' then 1 else 0 end as [IJ Section]
from #tmp
group by RowID , SectionName
这给出了这样的输出:
我需要这样的:
在此先感谢
正如@bill提到的,对于RECORD2 IJ的值是1。感谢。 –