limiting the rows to where the sum a column equals a certain value in MySQL

前端 未结 8 2483
闹比i
闹比i 2020-11-29 08:32

I want to write a query which returns all rows until the sum of one of the columns value reaches a certain value.

For example in the table below:

           


        
8条回答
  •  天涯浪人
    2020-11-29 09:16

    Hemant you do not state the RDBMS that use. Here is a script in t-sql that you can use in order to solve your problem.

    DECLARE @numberToReach INT;
    SET @numberToReach = 10; --you can change this
    
    DECLARE @date DATETIME;
    DECLARE @etc VARCHAR(20);
    DECLARE @meeting INT;
    DECLARE @temp_sum INT;
    
    CREATE TABLE #tempTable
        (
            Dates DATETIME,
            Etcs VARCHAR(20),
            Meeting INT,
        )
    
    DECLARE tempcursor CURSOR FOR
            SELECT *
            FROM YourTABLENAME
    OPEN tempcursor;
    FETCH NEXT FROM tempcursor INTO @date, @etc, @meeting;
    
    WHILE(@@FETCH_STATUS = 0)
    BEGIN
        SET @temp_sum = @temp_sum + @meeting;
        IF @temp_sum < @numberToReach 
        BEGIN
            INSERT INTO #tempTable
            (
                Dates,
                Etcs,
                Meeting
            )
            VALUES
            (
                @date, 
                @etc, 
                @meeting
            )
    
            FETCH NEXT FROM tempcursor INTO @date, @etc, @meeting;
        END 
    END
    
    SELECT * FROM #tempTable
    
    CLOSE tempcursor
    DEALLOCATE tempcursor
    
    DROP TABLE  #tempTable
    

提交回复
热议问题