简体   繁体   中英

Aggregating different rows in one column SQL Query

Sorry, I didn't come up with a good title for the question, so feel free to change it accordingly.

I may describe my question with a minimal example in 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');

I am trying to create a one row per record result in which every section is a column and if there is a row associated with a section, the corresponding column value is increased. This is (not) what I want (the same record data on different rows)

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

which gives this output:

错误的输出结果

I need this:

正确的输出

Thanks in advance

You can use pivot for this as below and manipulate the values of sections however you want.

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

I think the result you shown is not correct for record id 2. ij of record id 2 should be 1.

I think you want this:

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;

That is, you need aggregation functions. And the group by should contain the columns that you want to define each row (ie only the RowId ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM