我有一个表,我正在通过队列填充,我无法改变表的结构。
问题: 该表包含四个标识符 - SKU,Department,Class和Subclass - 我需要按照下面满足的第一个条件的顺序从表中返回其他字段:
我正在从这个表填充java应用程序中的报表字段,我不想写四个查询来检查这些情况。我不相信我能够执行任何程序性SQL,因此我需要通过本机SQL查询来执行此操作。
感谢任何帮助。
我不得不改变一下查询。以下查询有效:
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
答案 0 :(得分:0)
因此,您在查询中传递了4个参数(SKU,Department,Class和Subclass),并且需要参数的值字段。
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
查询的第一行是您所需要的。如何提取第一行取决于您使用的数据库