0

我有一个表,其中有两个字符串 user_id 和 user_activities_type 。exp。

'John',   '23Lqv'
'Mike', '159pLv3'

user_activities_type 中的每个单词都有自己的含义,例如

2-> take math lessons
3 -> take english lessons
L -> take chemical lessons

我想要的结果是

'John' ,'math,english,chemical'
'Mike','history,english,painting'

有没有办法通过 sql 来实现?

提前致谢!

4

2 回答 2

0

表:

users

    USER ACTIVITY_TYPE
    ---- ---------------
    John 23L
    Mike 159

activities

    ACTIVITY_CODE        DESCRIPTION
    -------------------- --------------------
    1                    music
    2                    math
    3                    english
    5                    physics
    9                    french
    L                    chemistry

询问:

select user_id, listagg(description, ',') within group (order by rk) as activities_list
from (select user_id, rk, description from users u join 
         (select rownum rk from all_tables) r on r.rk <= length(activity_type)
         join activities a on a.activity_code = substr(u.activity_type, rk, 1)  )
group by user_id
/

结果:

USER ACTIVITIES_LIST
---- --------------------------------------------------
John math,english,chemistry
Mike music,physics,french
于 2016-04-09T03:23:22.223 回答
0

你有一个非常非常非常糟糕的数据结构。我建议您将其更改为每个用户和每个活动一行,以及一个活动表。这是一种比较典型的规范化数据模型,比较适合关系型数据库。

但是,你可以这样做:

select user_id,
       concat_ws(',',
                 (case when user_activities_type like '%1%' then 'history' end),
                 (case when user_activities_type like '%2%' then 'math' end),
                 (case when user_activities_type like '%3%' then 'english' end),
                 . . .
                )
from t;

编辑:

哎呀。我没有意识到这是甲骨文。

select user_id,
       substr(',' || (case when user_activities_type like '%1%' then 'history' end) ||
              ',' || (case when user_activities_type like '%2%' then 'math' end) ||
              ',' || (case when user_activities_type like '%3%' then 'english' end)
                 . . .
               2)
from t;
于 2016-04-09T03:03:25.800 回答