TSQL - 具有范围的合并组?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TSQL - 具有范围的合并组?相关的知识,希望对你有一定的参考价值。

示例代码:

Declare  @table1 TABLE(myIndex int identity(1,1),[cal] int, Name Nvarchar(20) );
Declare @range int = 5; 

INSERT INTO @table1 ([cal], Name)
VALUES (1, 'A'), (3, 'B'), (4, 'C'), (2, 'D'), (3, 'E'), (4, 'F'), (6, 'G'), (2, 'H');

SELECT * FROM @table1

输出:

myIndex | Sum(cal) | Name |
--------+----------+------+    
   1    |   1      | A    | 
   2    |   3      | B    | 
   3    |   4      | C    | 
   4    |   2      | D    | 
   5    |   3      | E    |
   6    |   4      | F    |
   7    |   6      | G    |
   8    |   2      | H    |

我想Sum(cal) > 5然后加入字符串

SQL - 2012 - 报告期望示例

myIndex | Sum(cal) | Name   | Description
--------+----------+--------+--------------------------------   
    1   |   7      | A,B,C  | (Explain: First Sum(cal) > 5, Merge String)
    2   |   9      | D,E,F  | (Explain:Second Sum(cal) > 5, Merge String)
    3   |   6      | G      | (Explain:Third, Sum(cal) > 5, Merge String)
    4   |   2      | H      | (Explain:Last, still one last step)

请帮我解决问题。

答案

这是使用游标的解决方案。希望这可以帮助。试一试,看看性能是否可以接受。

Declare  @table1 TABLE(myIndex int identity(1,1),[cal] int, Name Nvarchar(20) );
Declare @range int = 5; 

INSERT INTO @table1 ([cal], Name)
VALUES (1, 'A'), (3, 'B'), (4, 'C'), (2, 'D'), (3, 'E'), (4, 'F'), (6, 'G'), (2, 'H');

SELECT * FROM @table1

-----
DECLARE @aggregates TABLE (myIndex int identity(1,1),SumCal int, AggregateNames Nvarchar(MAX) );
DECLARE @SumCal INT
      , @AggregateNames NVARCHAR(MAX)
      , @cal INT
      , @Name Nvarchar(20)
      ;

SET @SumCal = 0;
SET @AggregateNames = NULL;

DECLARE cur CURSOR LOCAL FAST_FORWARD FOR
SELECT [cal], name from @table1 ORDER BY myIndex

OPEN cur

FETCH NEXT FROM cur INTO @cal, @Name
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @SumCal = @SumCal + @cal
    SET @AggregateNames = ISNULL(@AggregateNames + ',', '') + @Name
    IF @SumCal > 5
       BEGIN
            INSERT INTO @aggregates([SumCal], AggregateNames)
            VALUES(@SumCal, @AggregateNames)

            SET @SumCal = 0
            SET @AggregateNames = NULL
       END

    FETCH NEXT FROM cur INTO @cal, @Name
END

IF @SumCal > 0
   BEGIN
    INSERT INTO @aggregates([SumCal], AggregateNames)
    VALUES(@SumCal, @AggregateNames)
   END

CLOSE cur

DEALLOCATE cur 

SELECT * FROM @aggregates

以上是关于TSQL - 具有范围的合并组?的主要内容,如果未能解决你的问题,请参考以下文章

TSQL 合并:<WHEN NOT MATCHED> 不跳过重复项

TSQL - 每组删除除 1 之外的所有行

TSQL - 排除与临时表匹配的行

tsql 将列合并到一张表中

具有动态偏移量的 TSQL 复制 LAG() 函数

分页功能 与 分类查询功能合并