我必须通过某些列来整理我的数据,以便首先显示某些特定值。所以对于像这样的查询...
SELECT rtrim(taskid) into v_taskid FROM tasks
where
/* some where clausers */
and rownum = 1
...我的基础是case when
,但困扰我的是我现在拥有的三个嵌套选择:
SELECT rtrim(taskid) into v_taskid FROM tasks where taskid in (
select taskid from (
select taskid,
case when taskuser like '%myuser%'
then 0
else 100
end as ordervalue
FROM tasks
where
/* some where clausers */
order by ordervalue
)
)
and rownum = 1
表现方面我认为它不应该是一个问题,但它看起来像一个意大利面......有没有办法将case-when
放入where
条款?
答案 0 :(得分:3)
您要查询tasks
表两次。这不是必需的,会使您的查询运行缓慢。您的查询可以组合成一个简单的查询,如下所示:
SELECT rtrim(taskid) into v_taskid
FROM (
SELECT taskid
FROM tasks
WHERE /* some where clauses */
ORDER BY case when taskuser like '%myuser%' then 0 else 100 end
)
WHERE rownum = 1;
然后,只需检索第一行或在外部查询中添加rownum部分。
答案 1 :(得分:1)
用户row_number() over (...)
select
taskid
from (
select
taskid,
row_number() over (
order by
case when taskuser like '%myuser%' then 0
else 100
end
) r
from
tasks
WHERE
/* some where clausers */
)
where
r = 1;
答案 2 :(得分:1)
如果taskid
是tasks
的主键,则不需要自联接(外部SELECT):
SELECT rtrim(taskid)
FROM (SELECT taskid
FROM tasks
/* where clause */
ORDER BY CASE
WHEN taskuser LIKE '%myuser%' THEN
0
ELSE
100
END)
WHERE ROWNUM = 1