代码之家  ›  专栏  ›  技术社区  ›  ASH

如何使用Max函数筛选列表并插入

  •  0
  • ASH  · 技术社区  · 5 年前

    有什么方法可以做到:

    Insert Into (col1, col2, col3)
    Select col1, col2, col3, max(col4)
    From mytable
    Group By col1, col2, col3
    

    这给了我: The select list for the INSERT statement contains more items than the insert list.

    我想使用max函数过滤掉重复项,但是当我选择这个额外的字段时,字段的顺序和字段的数量不匹配。如何从表中筛选列表、使用max函数以及插入除max字段中的记录之外的所有记录?

    2 回复  |  直到 5 年前
        1
  •  1
  •   GMB    5 年前

    我想用max函数来过滤掉欺骗

    好吧,我想你真的想 distinct :

    insert into my_target_table(col1, col2, col3)
    select distinct col1, col2, col3 from my_source_table
    

    这将在目标表中为每个不同的 (col1, col2, col3) 源表中的元组。

        2
  •  1
  •   Gordon Linoff    5 年前

    你这样描述:

    Insert Into (col1, col2, col3)
        select col1, col2, col3
        from mytable
        where t.col4 = (select max(t2.col4)
                        from mytable t2
                        where t2.col1 = t.col1 and t2.col2 = t.col2 and t2.col3 = t.col3
                       );
    

    然而,这相当于 select distinct ( NULL 价值观可能会被区别对待)。你可能只想在一个列上定义欺骗,所以我想:

    insert into (col1, col2, col3)
        select col1, col2, col3
        from mytable
        where t.col4 = (select max(t2.col4)
                        from mytable t2
                        where t2.col1 = t.col1
                       );