使用嵌套case更新sql中的查询

4jb9z9bj  于 2021-08-13  发布在  Java
关注(0)|答案(2)|浏览(381)

我想要有一个使用嵌套case的更新查询;

  1. UPDATE mstsales
  2. SET test = '2017-18'
  3. WHERE salemonth > 3 AND saleyear = 2017 OR salemonth < 4 AND saleyear = 2018
  4. UPDATE mstsales
  5. SET test = '2018-19'
  6. WHERE salemonth > 3 AND saleyear = 2018 OR salemonth < 4 AND saleyear = 2019
  7. UPDATE mstsales
  8. SET test = '2019-20'
  9. WHERE salemonth > 3 AND saleyear = 2019 OR salemonth < 4 AND saleyear = 2020
5us2dqdw

5us2dqdw1#

你可以做:

  1. UPDATE mstsales
  2. SET test = (CASE WHEN salemonth > 3 and saleyear = 2017 or salemonth < 4 and saleyear = 2018 THEN '2017-18'
  3. WHEN salemonth > 3 and saleyear = 2018 or salemonth < 4 and saleyear = 2019 THEN '2018-19'
  4. WHEN salemonth > 3 and saleyear = 2019 or salemonth < 4 and saleyear = 2020
  5. END)
  6. WHERE (salemonth > 3 and saleyear = 2017 or salemonth < 4 and saleyear = 2018) OR
  7. (salemonth > 3 and saleyear = 2018 or salemonth < 4 and saleyear = 2019) OR
  8. (salemonth > 3 and saleyear = 2019 or salemonth < 4 and saleyear = 2020)

我不认为这简化了逻辑。
你没有提到你的数据库。但也有更清洁的替代品:
使用计算列。
使用参考表。
使用派生表进行更新。

ugmeyewa

ugmeyewa2#

希望这有帮助。。

  1. UPDATE mstsales
  2. SET test = CASE
  3. WHEN salemonth > 3 and saleyear = 2017 or salemonth < 4 and saleyear = 2018 THEN '2017-18'
  4. WHEN salemonth > 3 and saleyear = 2018 or salemonth < 4 and saleyear = 2019 THEN '2018-19'
  5. WHEN salemonth > 3 and saleyear = 2019 or salemonth < 4 and saleyear = 2020 THEN '2019-20'
  6. END

如果所有情况都有一个共同的条件,那么进入where子句。

相关问题