当T-SQL中存在重叠时如何编写case语句

时间:2017-08-02 15:58:14

标签: sql-server tsql

我有一张这样的表

enter image description here

如何将其分组到此

enter image description here

小是计数<25时的计数总和;当Count> = 25时,大是计数的总和;总数是所有计数的总和。

3 个答案:

答案 0 :(得分:4)

尝试这样......

IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL 
DROP TABLE #TestData;

CREATE TABLE #TestData (
    ID INT NOT NULL  PRIMARY KEY,
    nCount int NOT NULL 
    );
INSERT #TestData (ID, nCount) VALUES
    (1, 10), (2, 15), (3, 22), (4, 23),
    (5, 25), (6, 27), (7, 30);

--=====================================

WITH 
    cte_Totals AS (
        SELECT 
            Total = SUM(td.nCount),
            Small = SUM(CASE WHEN td.nCount < 25 THEN td.nCount ELSE 0 END),
            Large = SUM(CASE WHEN td.nCount >= 25 THEN td.nCount ELSE 0 END)
        FROM 
            #TestData td
        )
SELECT 
    x.[Group],
    x.[Count]
FROM 
    cte_Totals t
    CROSS APPLY (VALUES (1, 'Total', t.Total), (2, 'Small', t.Small), (3, 'Large', t.Large) ) x (SortBy, [Group],[Count])
ORDER BY 
    x.SortBy;

结果...

Group Count
----- -----------
Total 152
Small 70
Large 82

HTH, 杰森

答案 1 :(得分:3)

最简单的方法是使用CASE

SELECT
     SUM(Count) as Total,
     SUM(CASE WHEN Count <  25 THEN Count ELSE 0 END) as Small,
     SUM(CASE WHEN Count >= 25 THEN Count ELSE 0 END) as Large
FROM table

答案 2 :(得分:3)

延迟回答(保持接受为),但我确实想介绍一个可能更有帮助的概念。

我维护一个通用的Tier表。以下是一个简化的示例,但您可以从代码中取出聚合层,并将其放在表中......事情会发生变化,您可以为多个主服务器提供服务。

示例数据

Declare @YourTable table (ID int,[Count] int)
Insert Into @YourTable values
(1, 10), (2, 15), (3, 22), (4, 23), (5, 25), (6, 27), (7, 30)

Declare @Tier table (Tier varchar(50),Seq int,Title varchar(50),R1 int,R2 int)
Insert Into @Tier values
 ('MyGroup',1,'Total',0,99999)
,('MyGroup',2,'Small',0,25)
,('MyGroup',3,'Large',25,99999)

实际查询

Select T.Title
      ,[Count] = sum(D.[Count])
 From  @Tier T
 Join  @YourTable D on (T.Tier='MyGroup' and D.Count >= T.R1 and D.Count<T.R2)
 Group By T.Title,T.Seq
 Order By T.Seq

<强>返回

Title   Count
Total   152
Small   70
Large   82
  

编辑 - 您可以通过多种方式构建

示例

Declare @YourTable table (ID varchar(50),[Count] int)
Insert Into @YourTable values
('Tywin', 10), ('Tywin', 15), ('Tyrion', 22), ('Bran', 23), ('Ned', 25), ('John', 27), ('Robb', 30)

Declare @Tier table (Tier varchar(50),Seq int,Title varchar(50),R1 int,R2 int,C1 varchar(50),C2 varchar(50))
Insert Into @Tier values
 ('MyGroup',1,'Total'  ,null,null,'a','z')
,('MyGroup',2,'Group 1',null,null,'Tywin,Tyrion',null)
,('MyGroup',3,'Group 2',null,null,'Bran,Ned,John,Robb',null)


Select T.Title
      ,[Count] = sum(D.[Count])
 From  @Tier T
 Join  @YourTable D on T.Tier='MyGroup' and (D.ID between C1 and C2 or patindex('%,'+D.ID+',%',','+C1+',')>0)
 Group By T.Title,T.Seq
 Order By T.Seq

<强>返回

Title     Count
Total     152
Group 1   47
Group 2   105