简体   繁体   中英

SQL Merge table rows based on IN criteria

I have a table result like following

Code    Counts1    Counts2   TotalCounts
1       10         20        30
4       15         18        33
5       5          14        19
...     ...        ...       ...

What I am trying to achieve is merging counts for all rows where Code (the column counts are grouped on) belongs IN (1,4). However, within all my research, all I found was methods to merge rows based on a common value for each row (same id, etc.)

Is there a way to merge rows based on IN criteria, so I know if I should research it further?

How about a union?

select
   1 as Code,
   sum(Counts1) as Counts1,
   sum(Counts2) as Counts2,
   sum(TotalCount) as TotalCounts
from
   YourTable
where
   code in (1,4)

union
select * 
from 
   YourTable
where 
   code not in(1,4)

Just assuming you will have numerous groupings (See the @Groupings mapping table)

You can have dynamic groupings via a LEFT JOIN

Example

Declare @YourTable Table ([Code] varchar(50),[Counts1] int,[Counts2] int,[TotalCounts] int)
Insert Into @YourTable Values 
 (1,10,20,30)
,(4,15,18,33)
,(5,5,14,19)

Declare @Groupings Table (Code varchar(50),Grp int)
Insert Into @Groupings values
 (1,1)
,(4,1)


select code    = Isnull(B.NewCode,A.Code)
      ,Counts1 = sum(Counts1)
      ,Counts2 = sum(Counts2) 
      ,TotalCounts = sum(TotalCounts)
 From  @YourTable A
 Left Join (
        Select *
              ,NewCode = (Select Stuff((Select ',' + Code From @Groupings Where Grp=B1.Grp For XML Path ('')),1,1,'') )
         From  @Groupings  B1
       ) B on (A.Code=B.Code)
 Group By Isnull(B.NewCode,A.Code)

Returns

code    Counts1 Counts2 TotalCounts
1,4     25      38      63
5       5       14      19

If it helps with the Visualization, the subquery generates

Code    Grp NewCode
1       1   1,4
4       1   1,4

sum the count, remove code from the select statement. Add a new column to group 1 and 4 using case statement lets name this groupN. then in SQL group it by groupN.

You are correct, grouping has to be based on common value. so by creating a new column, you are making that happen.

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