简体   繁体   English

基于IN条件的SQL合并表行

[英]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). 我想要实现的是合并代码(列计数分组于其上)属于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.) 但是,在我所有的研究中,我发现的都是基于每行的公共值(相同ID等)合并行的方法。

Is there a way to merge rows based on IN criteria, so I know if I should research it further? 有没有一种方法可以基于IN准则合并行,所以我知道是否应该对其进行进一步研究?

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) 仅假设您将有许多分组(请参见@Groupings映射表)

You can have dynamic groupings via a LEFT JOIN 您可以通过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. 对计数求和,从select语句中删除代码。 Add a new column to group 1 and 4 using case statement lets name this groupN. 使用case语句将新列添加到第1组和第4组中,让该组命名为N。 then in SQL group it by groupN. 然后在SQL中按groupN对其进行分组。

You are correct, grouping has to be based on common value. 您是正确的,分组必须基于共同值。 so by creating a new column, you are making that happen. 因此,通过创建新列,您可以实现这一目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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