SELECT DISTINCT lr.id,
lr.dept,
lr.name
Case When lr.id IN (SELECT id FROM RESULTS WHERE PANEL_FLAG LIKE '%value1%') AND lr.id IN (SELECT id FROM RESULTS WHERE PANEL_FLAG LIKE '%value2%') Then 1
Else 0
End As both_panels,
Case When lr.id IN (SELECT id FROM RESULTS WHERE PANEL_FLAG LIKE '%value1%') AND lr.id NOT IN (SELECT id FROM RESULTS WHERE PANEL_FLAG LIKE '%value2%') Then 1
Else 0
End As only_value1_panel,
FROM RESULTS lr
我已经简化了这个过程,实际上我实际上需要更多的Case While语句,这是性能的噩梦,因为子查询每次都执行。有更高效的方法可以做到这一点吗?
我尝试在查询之前创建通用表表达式和临时表,但是这样做的方式(用CTE或临时表中的SELECT替换子查询语句)似乎没有任何性能差异,因为每次仍在执行查询。
答案 0 :(得分:0)
通常使用条件聚合来处理。我认为这符合您的逻辑:
SELECT lr.id, lr.dept, lr.name,
LEAST(MAX(Case When PANEL_FLAG LIKE '%value1%' THEN 1 ELSE 0 END),
MAX(Case When PANEL_FLAG LIKE '%value2%' THEN 1 ELSE 0 END)
) As both_panels,
LEAST(MAX(Case When PANEL_FLAG LIKE '%value1%' THEN 1 ELSE 0 END),
MAX(Case When PANEL_FLAG LIKE '%value2%' THEN 0 ELSE 1 END)
) as only_value1_panel,
FROM RESULTS lr
GROUP BY lr.id, lr.dept, lr.name
答案 1 :(得分:0)
如果“ in”列表中的子查询带有“ constant”子句,我会考虑将它们填充到脚本(逗号和全部)中,然后将其注入“ sql template”文件并运行。 那将非常快地运行。 当然,生成的列表应该很小(所有列表的总数都小于60KB),否则sql语句将变得太大。