TSQL - 具有范围的合并组?

问题描述 投票:0回答:1

示例代码:

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)

请帮我解决问题。

tsql sql-server-2012 group-by count range
1个回答
0
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.