對不起,我沒有拿出一個好問題的標題,所以隨意相應地改變它。在一列中聚合不同的行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。感謝。 –