保留前N行,删除其余行

时间:2014-09-16 12:58:13

标签: sql db2 udb

尝试编写一个sql,它将保留表的前N行,并删除其余的行。我已经知道了这个sql,但它说我不能在这里使用计数。请帮我重写sql。

DELETE 
  FROM ZZ_TEST_FINTABLE
 WHERE PROCESS_INSTANCE = ( 
 SELECT MIN(B.PROCESS_INSTANCE) 
  FROM ZZ_TEST_FINTABLE B) 
   AND COUNT(PROCESS_INTANCE) > 9

3 个答案:

答案 0 :(得分:0)

您应该使用HAVING而不是AND。

   DELETE 
   FROM ZZ_TEST_FINTABLE
   WHERE PROCESS_INSTANCE = ( 
                            SELECT MIN(B.PROCESS_INSTANCE) 
                             FROM ZZ_TEST_FINTABLE B
                            ) 
   HAVING COUNT(PROCESS_INTANCE) > 9

或者

    DELETE 
    FROM ZZ_TEST_FINTABLE A
    INNER JOIN ZZ_TEST_FINTABLE B ON A.PROCESS_INSTANCE= MIN(B.PROCESS_INSTANCE)
    HAVING COUNT(PROCESS_INTANCE) > 9

答案 1 :(得分:0)

也许这适合您(使用Oracle DB)

DELETE FROM
    ZZ_TEST_FINTABLE 
WHERE
    PROCESS_INSTANCE NOT IN 
    (
        SELECT PROCESS_INSTANCE 
        FROM ZZ_TEST_FINTABLE 
        WHERE ROWNUM < 9
    );

答案 2 :(得分:0)

您必须为您的表修改此内容,但应该可以使用:

DELETE FROM myschema.mytable WHERE pkey NOT IN (SELECT pkey FROM myschema.mytable ORDER BY pkey FETCH FIRST 10 ROWS ONLY)