代码之家  ›  专栏  ›  技术社区  ›  Victor Barreto

根据SQL中的条件更新日期时间列

sql
  •  -1
  • Victor Barreto  · 技术社区  · 2 年前

    我有下表:

    身份证件 订单日期 交货日期
    1. 2023-01-23 2023-01-26
    2. 2023-05-21 2023-05-29
    3. 2023-06-03 2023-06-01
    4. 2023-07-04 2023-07-20
    5. 2023-08-21 2023-07-21

    在第3行和第5行中,交货日期小于订单日期。因此,在这些情况下,我将假设delivery_date=order_date。

    因此,我创建了以下查询:

    SELECT*,(case delivery_date<order_date then delivery_date = order_date else delivery_date=delivery_date end) as delivery_date_is_assumed
    from table
    

    上面的查询不起作用。我需要以下输出:

    身份证件 订单日期 交货日期
    1. 2023-01-23 2023-01-26
    2. 2023-05-21 2023-05-29
    3. 2023-06-03 2023-06-03
    4. 2023-07-04 2023-07-20
    5. 2023-08-21 2023-08-21
    1 回复  |  直到 2 年前
        1
  •  1
  •   Schwern    2 年前

    有两个问题。

    基本的大小写语法是这样的。

     CASE
        WHEN condition1 THEN result1
        WHEN condition2 THEN result2
        WHEN conditionN THEN resultN
        ELSE result
    END
    

    你错过了第一个 when .

    您没有分配给列,只需给出所需的值即可。

    SELECT
      id, order_date
      case
        when delivery_date<order_date then order_date 
        else delivery_date
      end as delivery_date
    from table
    

    看见 w3schools SQL Case Expression