sql - 如何在 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
我不确定如何添加我的关闭商店条件。谁能帮我完成这个查询?任何帮助,将不胜感激。谢谢你。
解决方案
如果您想检查另一种可能性,您可以在语句中添加另一个WHEN
或ELSE
条件。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 中可能不是一回事。
推荐阅读
- python - 为什么在字典中获取时只打印最后一行也需要用 0 替换 None
- javascript - addEventListener - 如果未点击语句如何制作
- amazon-web-services - 无法从系统设置加载凭据。AWS_ACCESS_KEY_ID
- substrate - 调度在另一个 Substrate FRAME 托盘中定义的函数
- php - 如何不能两次显示相同的信息或数据
- mysql - MySQL 8.0.20 错误?使用 GROUP BY 和 COUNT(DISTINCT) 时产生的组重复
- image - 如何从颤动的图像中获得主色?
- azure - Azure KeyVault 配置共享
- symfony - 从 App\Entity\CINFO\CiRome 到 App\Entity\CINFO\CiFormacode 的关系引用的列名“FCO_ID”不存在
- javascript - 我可以在 Node.js 和 Express 中运行单个 .js 文件吗?