我有一个问题组表,如下所示:
ID, NAME, DESCRIPTION, VERSION_ID
版本表列是:
ID, NUMBER, VERSION_STATE
VERSION_STATE
是枚举的,可以是0,1或2.
我需要选择其版本具有v VERSION_STATE
0或1的所有问题组,但如果有问题组且VERSION_STATE = 0
我不必返回问题组使用VERSION_STATE = 1
。
最简单的方法是:
SELECT distinct QG.id FROM healthsafety.hs_questions_group QG
LEFT OUTER JOIN (SELECT * FROM healthsafety.hs_version) VERSION
ON QG.VERSION_ID = VERSION.ID
WHERE
VERSION.VERSION_STATE=0
OR VERSION.VERSION_STATE=1
问题是此查询返回所有问题组VERSION_STATE
0或1.如果我删除or子句,并且没有VERSION_STATE = 0
的问题组,我需要返回问题VERSION_STATE = 1
的小组。
我认为我需要一个if else或case声明,但我被困了。有什么想法吗?
请注意,我必须使用条件来实现此功能,因此我需要使用最简单的解决方案。
答案 0 :(得分:1)
SELECT *
FROM (
SELECT OG.ID,OG.NAME,OG.DESCRIPTION,VERSION.ID,VERSION.NUMBER,VERSION.VERSION_STATE,ROW_NUMBER()OVER(PARTITION BY OG.ID ORDER BY VERSION.VERSION_STATE ASC) as INDICATOR
FROM healthsafety.hs_questions_group QG
LEFT OUTER JOIN
(SELECT * FROM healthsafety.hs_version) VERSION
ON QG.VERSION_ID = VERSION.ID
WHERE
VERSION.VERSION_STATE=0
OR VERSION.VERSION_STATE=1
) AS ABC
WHERE (ABC.VERSION_STATE = 0 and ABC.INDICATOR = 1)
OR (ABC.VERSION_STATE = 1 and ABC.INDICATOR = 1)
答案 1 :(得分:0)
使用common table expression和union all
,其中第二个查询使用not exists()
仅返回version_state=1
的行,而version_state=0
行不存在。< / p>
;with cte as (
select qg.id, v.version_state
from healthsafety.hs_questions_group qg
inner join healthsafety.hs_version version v
on qg.version_id = v.id
where v.version_state in (0,1)
)
select id
from cte
where version_state = 0
union all
select qg.id
from cte
where version_state = 1
and not exists (
select 1
from cte
where version_state = 0
)