首页 > 解决方案 > 如何在 SQL 查询中添加条件语句?

问题描述

嗨,我正在处理一个 SQL 查询。下面是我执行查询的方法名称。

private string GetAggregatedOptionParametersByStyleIdCommand(string styleId, bool currentStore)
    {
      SELECT
      opts.style, opts.option::text as {OptionKey}, opts.primary_colour, opts.secondary_colour, opts.brand_description, opts.description, params.*,
    CASE WHEN {currentStore} == true THEN 
    FROM
      rex.options opts
    JOIN
      rex.product_atoms atoms ON atoms.option_id = opts.option
    JOIN
      rex.parameters params ON atoms.id = params.product_atom_id
    JOIN
      rex.stores stores ON params.store = stores.id
    WHERE
      opts.style = '{styleId}'
  }

下面是stores表的结构。

CREATE TABLE rex.stores (
    id serial NOT NULL,
    close_date timestamp NOT NULL,
    country text NULL,
    distribution_centre text NULL,
    "name" text NULL,
    open_date timestamp NOT NULL,
    CONSTRAINT "PK_stores" PRIMARY KEY (id)
);

所以我想做的是,只要 currentStore 为真,我就想返回当前商店。检查 currentStore 的条件是

 store.OpenDate <= currentDate &&
          store.CloseDate >= currentDate

每当 currentStore 为 false 时,我都想返回所有商店。检查所有商店的状况是

store.CloseDate >= currentDate

我正在尝试在 SQL 查询中添加这些条件。我添加了CASE WHEN {currentStore} == true THEN我不确定如何添加我的关闭商店条件。谁能帮我完成这个查询?任何帮助,将不胜感激。谢谢你。

标签: sqlpostgresql

解决方案


如果您想检查另一种可能性,您可以在语句中添加另一个WHENELSE条件。CASE这些都需要在END.

例如:

CASE
    WHEN x < 0 THEN 'negative'
    WHEN x > 0 THEN 'positive'
    ELSE 'zero'
END

我不熟悉postgres,你可能不需要一个END,你也可以说CASE x WHEN > 0 THEN... WHEN < 0 ...你只需要在后面提到一次x CASE;同样,这在 postgres 中可能不是一回事。


推荐阅读