Oracle SQL:按组和子条目枚举行

维克多·阿达托

我有一张这样的桌子

Question_Id   Question_text   Question_Answer_id     Date  
------------  --------------  ------------------     --------
1             First Question                         1-1-2021
2             First Answer    1                      2-1-2021
3             Second Answer   1                      3-1-2021
4             Random Question                        4-1-2021
5             Random Answer   4                      5-1-2021
6             Another Answer  4                      6-1-2021

我需要显示类似于以下 SELECT 的内容

Question_Id   Question_text   Question_Answer_id     Date       Order
------------  --------------  ------------------     --------   --------
1             First Question                         1-1-2021   001
2             First Answer    1                      2-1-2021   001.001
3             Second Answer   1                      3-1-2021   001.002
4             Random Question                        4-1-2021   002
5             Random Answer   4                      5-1-2021   002.001
6             Another Answer  4                      6-1-2021   002.002

我需要使用 SELECT 显示新订单,此订单列​​基于具有答案 ID 的条目。我尝试使用函数 Row_number() 但我无法正确使用。

订单不是另一张桌子

我怎样才能进行这种类型的枚举?

戈登·利诺夫

假设您的层次结构只有两个深(这对问题/答案有意义),您可以使用窗口函数。特别是,您可以使用dense_rank()为问题分配一个数字,然后dense_rank()再次为每个问题中的答案分配一个数字剩下的只是格式化最终的字符串:

select t.*,
       (lpad(dense_rank() over (order by coalesce(t.Question_Answer_id, t.question_id)), 3, '0') ||
        (case when t.Question_Answer_id is not null
              then '.' || lpad(dense_rank() over (partition by t.Question_Answer_id order by t.question_id), 3, '0')
         end))
from t
order by question_id;

是一个 db<>fiddle。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章