2016-09-18 75 views
1

对不起,我没有拿出一个好问题的标题,所以随意相应地改变它。在一列中聚合不同的行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 

这给出了这样的输出:

Wrong Output Result

我需要这样的:

Correct Output

在此先感谢

+0

正如@bill提到的,对于RECORD2 IJ的值是1。感谢。 –

回答

1

我想你想要这个:

select RowID, 
     sum(case when SectionName = 'AB' then 1 else 0 end) as [AB Section] , 
     sum(case when SectionName = 'CD' then 1 else 0 end) as [CD Section] , 
     sum(case when SectionName = 'EF' then 1 else 0 end) as [EF Section] , 
     sum(case when SectionName = 'GH' then 1 else 0 end) as [GH Section] , 
from #tmp 
group by RowID; 

也就是说,你需要聚合函数。 group by应包含您想要定义每一行的列(即只包含RowId)。

+0

“对应列值增加”暗示'sum(.. 1.0)'我猜。 – Serg

+0

@Serg。 。 。这就说得通了。样本数据不区分这两种情况。 –

2

您可以像下面一样使用pivot来操作不同部分的值。

SELECT rowid 
,CASE 
    WHEN ab IS NULL 
     THEN 0 
    ELSE 1 
    END AS ab 
,CASE 
    WHEN cd IS NULL 
     THEN 0 
    ELSE 1 
    END AS cd 
,CASE 
    WHEN ef IS NULL 
     THEN 0 
    ELSE 1 
    END AS ef 
,CASE 
    WHEN gh IS NULL 
     THEN 0 
    ELSE 1 
    END AS gh 
,CASE 
    WHEN ij IS NULL 
     THEN 0 
    ELSE 1 
    END AS ij 
FROM (
SELECT * 
FROM #tmp 
PIVOT(MAX(Sectioncode) FOR Sectionname IN (
      AB 
      ,CD 
      ,EF 
      ,GH 
      ,IJ 
      )) pvt 
) tab 

我想你显示的结果是不备案编号是否正确2.记录ID 2的IJ应为1

+0

谢谢,您的解决方案是否更好的性能?这对我来说似乎更加复杂。 –