sql—根据对其他列的查询,删除mysql表中特定列的重复值

cl25kdpy  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(258)

我在sql数据库中有一个表,记录特定产品的客户销售情况。我有如下每个产品的每月目标
产品a-50件
现在在我的表格中,我看到了客户销售和每月产品销售目标,这是常见的。

Customer    Product     MonthlyTargetQty
Customer A  Product 1       50
Customer B  Product 1       50
Customer C  Product 1       50
Customer D  Product 1       50

我只想在monthlytargetty列中保留不同的值,不想删除在product列中重复的product name。请帮忙询问
我想要的是:-

Customer    Product     MonthlyTargetQty
Customer A  Product 1       50
Customer B  Product 1       0
Customer C  Product 1       0
Customer D  Product 1       0
a2mppw5e

a2mppw5e1#

从评论看来,你想更新我添加了更新

with cte as
    (
    select customer, product,
           (case when row_number() over (partition by product order by customer) = 1 then monthlytargetqty end) as monthlytargetqty
    from t
    )
  update a 
  set a.MontylyTargetQty= b.monthlytargetqty
  from ProductAnalysisTable a join cte on
a.customer=cte.customer and a.product=b.product

顺便说一句,第一部分是戈登先生,所以接受他的回答

wvt8vs2t

wvt8vs2t2#

你似乎想要:

select customer, product,
       (case when row_number() over (partition by product order by customer) = 1 then monthlytargetqty end) as monthlytargetqty
from t
order by product, customer;

它使用 row_number() 为每个客户定义第一行,然后定义 case 表达式来保留该行上所需的值。请注意 order by 符合 partition by / order by 为了 row_number() .
编辑:
如果要更新现有表(我觉得这是个非常糟糕的主意),可以执行以下操作:

update t join
       (select product, min(customer) as min_customer
        from t
        group by product
       ) tt
       on t.product = tt.product and t.customer <> tt.min_customer
    set monthlytargetqty = 0;

相关问题