查询结构问题

时间:2019-02-04 20:27:49

标签: sql oracle

我有一个要求:

user id    full role                           
a123456    abcd:READ_ONLY     
a123456    fghi:READ_ONLY                  

我的目标是使用不同的关键字获取这两行:

我正在使用以下查询:

select distinct 
         user id,
         SUBSTR(full role, INSTR(full role, ':')+1) end as ROLE
from table 

但是我只能实现一行。您能帮我吗。我不想从查询中删除与众不同的内容,因为还有很多其他角色可用,其中完全角色可以相同。

a123456     READ_ONLY
a123456     READ_ONLY

2 个答案:

答案 0 :(得分:1)

也许伯爵会做你想做的事?

select user id,
       SUBSTR(full role, INSTR(full role, ':')+1) as ROLE,
       count(*) as num_times
from table 
group by user_id;

答案 1 :(得分:0)

如果要输出特定角色的所有行,而仅输出其他行,则可以执行以下操作:

WITH your_table AS (SELECT 'a123456' user_id, 'abcd:READ_ONLY' full_role FROM dual UNION ALL
                    SELECT 'a123456' user_id, 'fghi:READ_ONLY' full_role FROM dual UNION ALL
                    SELECT 'a123456' user_id, 'zyxw:WRITE' full_role FROM dual UNION ALL
                    SELECT 'a123456' user_id, 'vuts:WRITE' full_role FROM dual)
SELECT user_id,
       role
FROM   (SELECT DISTINCT user_id,
                        SUBSTR(full_role, INSTR(full_role, ':') + 1) AS role,
                        CASE
                          WHEN SUBSTR(full_role, INSTR(full_role, ':') + 1) = 'READ_ONLY' THEN
                           rownum
                          ELSE
                           NULL
                        END rn
        FROM   your_table)
ORDER BY user_id, ROLE;

USER_ID ROLE
------- --------------
a123456 READ_ONLY
a123456 READ_ONLY
a123456 WRITE

这似乎有点奇怪;我很想听听更多关于您为什么需要这个的信息。