【问题标题】:Conditional columns in select statement based on parameters基于参数的select语句中的条件列
【发布时间】:2020-04-06 12:22:33
【问题描述】:

我有以下条件:

- If ouk_shipment.shipper_parent_id = Parameter1 OR
ouk_shipment.shipper_id = Parameter2
=====> ouk_shipment.first_mwb_ref_id
- If ouk_shipment.cnee_parent_id = Parameter1 OR
ouk_shipment.cnee_id = Parameter2
=====> ouk_shipment.last_mwb_ref_id

**Parameter1和Parameter2:我们在SQL运行时输入。

我在这里尝试实现以下目标:

Select case when condition 1=True then ouk_shipment.first_mwb_ref_id
            when condition 2=True then ouk_shipment.last_mwb_ref_id End AS Col1
From ouk_shipment

如何在我的 SQL 中添加条件? 请检查

【问题讨论】:

    标签: sql oracle select parameters conditional-statements


    【解决方案1】:

    你可以这样做 - 注意我做了 'XXX' 假设它是 varchar,你可以将它更改为 Integer for Int

    SELECT CASE WHEN  ouk_shipment.shipper_parent_id = COALESCE(Parameter1,'XXX') 
                          OR ouk_shipment.shipper_id = COALESCE(Parameter2,'YYYY')
                  THEN ouk_shipment.first_mwb_ref_id
                WHEN ouk_shipment.shipper_parent_id = COALESCE(Parameter1,'XXX') 
                    OR ouk_shipment.shipper_id = COALESCE(Parameter2,'YYYY')
                  THEN ouk_shipment.last_mwb_ref_id End AS Col1
    FROM ouk_shipment
    

    【讨论】:

    • 恐怕 CASE 语法错误。
    【解决方案2】:

    你99%都在那里

    select 
      case 
        when ouk_shipment.shipper_parent_id = Parameter1 OR ouk_shipment.shipper_id = Parameter2 then ouk_shipment.first_mwb_ref_id
        when ouk_shipment.cnee_parent_id = Parameter1 OR ouk_shipment.cnee_id = Parameter2 then ouk_shipment.last_mwb_ref_id
      end col  
    from  ouk_shipment
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-09
      • 2021-01-05
      • 2017-02-03
      • 2019-12-15
      • 2012-02-23
      • 1970-01-01
      • 2018-05-02
      • 2021-11-15
      相关资源
      最近更新 更多