根据另一个表中的记录数量使用ntile

时间:2014-07-22 13:40:15

标签: sql oracle

我想知道我的问题是否有解决方案。

我有一个标记列表。我使用ntile并将结果集中的每条记录分开。

SELECT id, 
       type,  
       CASE
         WHEN ntile(3) OVER(ORDER BY id) = 1 THEN 'Marker 1 blah dfg'
         WHEN ntile(3) OVER(ORDER BY id) = 2 THEN 'Marker 2 blah sdf dfg'
         WHEN ntile(3) OVER(ORDER BY id) = 3 THEN 'Marker 3 blah ad asa'
         ELSE 'OTHER'
       END AS Marker
 FROM TABLE1

如何使用表格实现它并从中动态获取标记列表而不是如上所示进行硬键入?

我需要实现类似的:

ntile(Select COUNT(*) from MARKERS_TABLE) OVER(ORDER BY id) = [MARKERS_TABLE.MARKER_RECORD_ID]
     THEN [MARKERS_TABLE.CORRESPONDING_MARKER_DESCRIPTION]

但如何循环1,2和3 ... n ?如何在上述场景中指定相应的值?

MARKERS_TABLE

MARKER_RECORD_ID | CORRESPONDING_MARKER_DESCRIPTION

TABLE1

ID | TYPE |案例|

2 个答案:

答案 0 :(得分:2)

您必须将常量传递给NTILE,因此标量子查询不起作用:

select t.val, m.value
from 
 (
   select val, 
      ntile(3) over (order by t.val) as ntile
   from t
 ) t 
join markers m
on m.id = t.ntile;

当然,您可以使用PL / SQL将计数作为参数传递。

如果您真的需要在纯SQL中动态计数,那么解决方法虽然效率较低,但请参阅fiddle

with cte(n) as
  (select count(*) from markers)
select t.val, m.value
from 
 (
   select val, 
      ntile(cte.n) over (partition by cte.n order by t.val) as ntile
   from t, cte
 ) t 
join markers m
on m.id = t.ntile
;

答案 1 :(得分:1)

merge
   into TABLE1 d
   using (
      select ID, MARKER_DESC
      from (select 
              t1.ID,
              ntile(count(0)) over(order by t1.ID) as marker_id
            from TABLE1 t1, MARKERS_TABLE
            group by t1.ID) 
      left join MARKERS_TABLE using (marker_id)
   ) s
   on (d.ID = s.ID)
when matched then update set
   MARKER = s.MARKER_DESC;

fiddle