【问题标题】:query to update row查询更新行
【发布时间】:2011-06-28 05:45:36
【问题描述】:

我有一个结构表:

Country |  DUPLICATE
India   |
Australia|
India   |
USA     |
Germany |
Germany |

当 Country 列中的值唯一时,我必须将 DUPLICATEcolumn 更新为“Y”,如果值不唯一,我必须将 DUPLICATEcolumn 更新为“N”。 我试图在

的帮助下完成此任务
select Country,dupe_count
count(*) over (partition by Country) as dupe_count
from newTable 

此查询将返回国家名称和一个 DUP 列(包含相应国家字段的出现次数)。 但没能做到。 任何想法如何做到这一点,或者有没有更好的方法来做到这一点。 请帮忙。

【问题讨论】:

    标签: sql oracle11g


    【解决方案1】:

    用下面的测试数据...

    create table tq84_country (
      country varchar2(10) , 
      duplicate char(1)  check(duplicate in ('Y', 'N'))
    );
    
    insert into tq84_country (country) values ('India');
    insert into tq84_country (country) values ('Australia');
    insert into tq84_country (country) values ('India');
    insert into tq84_country (country) values ('USA');
    insert into tq84_country (country) values ('Germany');
    insert into tq84_country (country) values ('Germany');
    

    ...这个更新语句应该做的:

    update
      tq84_country a
    set
      duplicate = (
        select 
          case when 
            count(*)  > 1 then 'Y' 
                          else 'N'
            end 
        from
          tq84_country b
        where
          a.country = b.country
    );
    

    验证:

    select * from tq84_country;
    

    【讨论】:

    • 哦,对不起,René Nyffenegger...这只是正确的:) 抱歉之前的评论...更新表格的好主意
    【解决方案2】:

    不太确定 oracle - 我已经很久没有使用它了。但从记忆来看,它与 mssql 并没有什么不同。

    UPDATE newTable 
    SET DUPLICATE = 'Y'
    WHERE Country IN (
       SELECT COUNT(Country)
       FROM newTable
       GROUP BY Country
       HAVING Count(Country) > 1
    )
    
    
    UPDATE newTable 
    SET DUPLICATE = 'N'
    WHERE Country IN (
       SELECT COUNT(Country)
       FROM newTable
       GROUP BY Country
       HAVING Count(Country) = 1
    )
    

    【讨论】:

      【解决方案3】:

      当值不唯一时,您要在重复列中放置“N”.. 表示具有重复记录的列 Country 的值,然后您要放置 N(否)

      您可以通过任何方式轻松使用以下查询来执行此任务

      update newTable  
      set DUPLICATE =
      case
      when country in (select country from newTable group by country having count(*) > 1) then 
      'N' -- if you got my previous point then you have to edit this line with 'Y'
      else
      'Y'
      end;
      

      【讨论】:

        猜你喜欢
        • 2011-04-21
        • 2018-02-04
        • 1970-01-01
        • 1970-01-01
        • 2019-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多