SQL";有条件的;where子句
我有一个通过队列填充的表,我无法更改表的结构 问题: 该表包含四个标识符—SKU、Department、Class和Subclass—我需要按照满足以下第一个条件的顺序从表中返回其他字段:SQL";有条件的;where子句,sql,Sql,我有一个通过队列填充的表,我无法更改表的结构 问题: 该表包含四个标识符—SKU、Department、Class和Subclass—我需要按照满足以下第一个条件的顺序从表中返回其他字段: 如果表中存在SKU,则获取SKU的值 否则,如果表中存在SKU的部门/类/子类,则获取 价值观 否则,如果表中存在SKU的部门/类别 获取价值 否则,如果表中存在SKU部门,则获取 价值观 否则,SKU没有适用的值(我不知道 (我认为这种情况会发生) 我正在从这个表填充java应用程序中的报告字段,我不想编写
Select dept, class, subclass,
case
when sku = :sku then 1
when dept = :dept and class = :class and subclass = :subclass then 2
when dept = :dept and class = :class then 3
when dept = :dept then 4
end as priority,
field1, field2, field3, field4, field5
From schema.table
where sku = :sku
or (dept = :dept and class = :class and subclass = :class)
or (dept = :dept and class = :class and subclass is null)
or (dept = :dept and class is null and subclass is null)
order by priority asc
) 因此在查询中传递4个参数(SKU、部门、类和子类),并需要参数的值字段
select
case
when sku=:sku then 1
when Department=:Department and Class=:Class and Subclass=:Subclass then 2
when Department=:Department and Class=:Class then 3
when Department=:Department then 4
end as priority,
<value field here>
from the_table t
where sku=:sku
or Department=:Department
or Class=:Class
or Subclass=:Subclass
order by priority
选择
案例
当sku=时:sku然后为1
当Department=:Department and Class=:Class and Subclass=:Subclass时,则为2
当Department=:Department和Class=:Class时,则为3
当Department=:Department然后是4
优先结束,,
从表t
其中sku=:sku
或部门=:部门
或类=:类
或子类=:子类
按优先顺序排列
查询的第一行是您需要的。如何提取第一行取决于您使用的数据库我遗漏了一些东西。您是在填充表还是在查询表?样本数据和期望的结果可以真正帮助解释您想要做什么。另外,用你正在使用的数据库标记问题。谢谢。正是我要找的。我没有考虑在结果字段中返回优先级。