SQL - 是否可以查找具有相同Group By的等于0的和?

时间:2017-08-29 16:08:49

标签: mysql sql

是否可以删除总和为0的行?

这是表:

+-----------+--------------+
| Subledger | ActualAmount |
+-----------+--------------+
| WWE12     | -217         |
| WWE12     | -43          |
| WWE12     | 260          |
+-----------+--------------+

,所需的结果应为:

moneytotf

非常感谢任何帮助。

非常感谢你!

2 个答案:

答案 0 :(得分:0)

这是非常人为的,因为我事先知道总和是由3个值组成,但无论如何......

SELECT x.*
  FROM 
     ( SELECT DISTINCT GROUP_CONCAT(DISTINCT c.actualamount ORDER BY c.actualamount) members
            , SUM(DISTINCT c.actualamount) total
         FROM my_table a 
         JOIN my_table b 
           ON b.actualamount NOT IN (a.actualamount)
         JOIN my_table c 
           ON c.actualamount NOT IN (a.actualamount,b.actualamount) 
        GROUP 
           BY a.actualamount
            , b.actualamount
       HAVING total = 0
     ) n
  JOIN my_table x
    ON FIND_IN_SET(actualamount,members) > 0;

答案 1 :(得分:0)

请试试这个:

SELECT  ROW_NUMBER() OVER ( ORDER BY ActualAmount DESC ) rw ,
        *
INTO    #Negative
FROM    your_table
WHERE   ActualAmount < 0;

SELECT  ROW_NUMBER() OVER ( ORDER BY ( SELECT   1
                                     ) ) rw ,
        *
INTO    #Positive
FROM    your_table
WHERE   ActualAmount > 0;


CREATE TABLE #FinalTable
    (
      Subledger NVARCHAR(50) NULL ,
      ActualAmount INT NULL
    );

DECLARE @NCounterMax INT= ( SELECT  COUNT(*)
                            FROM    #Negative
                          );
DECLARE @PCounterMax INT= ( SELECT  COUNT(*)
                            FROM    #Positive
                          ) ,
    @NC INT= 1 ,
    @PC INT= 1 ,
    @amount INT= 0 ,
    @amount2 INT= 0 ,
    @subledger NVARCHAR(50) ,
    @countinue BIT = 1 ,
    @SumAmount INT= 0;
WHILE ( @PC <= @PCounterMax )
    BEGIN
        SELECT  @amount = ActualAmount ,
                @subledger = Subledger
        FROM    #Positive
        WHERE   rw = @PC;
        INSERT  INTO #FinalTable
        VALUES  ( @subledger, @amount );
        SET @SumAmount = @amount;
        PRINT @amount;
        WHILE ( @NC <= @NCounterMax )
            BEGIN
                SELECT  @amount2 = ActualAmount ,
                        @subledger = Subledger
                FROM    #Negative
                WHERE   rw = @NC;
                INSERT  INTO #FinalTable
                VALUES  ( @subledger, @amount2 );
                SET @SumAmount = @SumAmount + @amount2;
                IF ( @SumAmount = 0 )
                    BEGIN
                        SET @countinue = 0;
                        BREAK;
                    END;
                SET @NC = @NC + 1;
            END;
        IF ( @countinue = 0 )
            BREAK;
        DELETE  #FinalTable;
        SET @PC = @PC + 1;
    END;
SELECT  *
FROM    #FinalTable;

DROP TABLE #Negative;
DROP TABLE #Positive;
DROP TABLE #FinalTable; 

您可以从表中删除#FinalTable条记录。