如果购买了一件商品,请将数量重置为零

时间:2015-05-07 13:54:01

标签: sql sql-server-2008

我正试图解决这个问题......

如果客户购买了第5件商品,我试图将5个商品的数量列重置为零。无论是否购买或退回该物品,都必须尊重另一栏。此列的值必须为“3337”,我只想在已购买/返回列值= 3337的行上将QTY字段重置为零

示例表:

Customer | Item # | Qty | Purchased / returned 
1        | 1      | 1   | 3337
1        | 2      | 2   | 3337
1        | 3      | 1   | 3337
1        | 4      | 1   | 3337
1        | 5      | 1   | 3337
1        | 1      | 1   | 1034
2        | 1      | 1   | 3337
2        | 3      | 1   | 3337
2        | 4      | 1   | 3337
2        | 2      | 1   | 3337
3        | 1      | 1   | 3337
4        | 1      | 1   | 3337

在我的示例表中,只有客户#1已达到第5项,因此我想将QTY字段重置为0,但仅限于已购买/返回列= 1034的行

结果应如下所示。

Customer | Item # | Qty | Purchased / returned 
1        | 1      | 0   | 3337
1        | 2      | 0   | 3337
1        | 3      | 0   | 3337
1        | 4      | 0   | 3337
1        | 5      | 0   | 3337
1        | 1      | 1   | 1034
2        | 1      | 1   | 3337
2        | 3      | 1   | 3337
2        | 4      | 1   | 3337
2        | 2      | 1   | 3337
3        | 1      | 1   | 3337
4        | 1      | 1   | 3337

1 个答案:

答案 0 :(得分:0)

对数据类型和简化列名做出一些假设:

UPDATE MyTable
 set Qty = 0
 where Purchased = 3337
  and Customer in (--  All purchasers of 3337 who got to Item 5
                   select Customer
                    from MyTable
                    where Item = 5
                     and Purchased = 3337
                     and Qty = 1)  --  Line added in after initial post