首页 > 解决方案 > 我需要编写一个查询以根据用户在单行中关联的所有类型返回 user_type

问题描述

我有一个带有用户列和user_type列的表。一个用户可以关联到多个 user_type。

该列中共有五个不同的 user_type。我需要找到与所有 user_type 相关联的每个用户。

例如:

User_type       User
--------------------
Teacher         AAAA
Principal       AAAA
Employee        AAAA
Admin           BBBB
Cashier         CCCC
Teacher         DDDD
Principal       DDDD
Employee        DDDD
Admin           EEEE
Cashier         EEEE

假设这是表(这只是一个示例表)。这里 AAAA 需要声明为 UT_NEW1
BBBB 为 UT_NEW2
CCCC 为 UT_NEW3
DDDD 再次声明为 UT_NEW1
和 EEEE 为 UT_NEW4。

在这种情况下我们不能使用 count,因为无法确定特定用户是否具有三个 user_type,然后可以将它们声明为特定组。

我正在尝试做:

如果 User = 'Some user' and his user_type = ('user_type1' and 'user_type2' and 'user_type3') 那么他/她可以被声明为 'type1'。

用户属于由特定 user_types 定义的组。只有当一个用户拥有那些特定的 user_types 而不是其他的,他们才能被声明为属于该组。

标签: sqloracle

解决方案


您总共有 5 种用户类型,因此您可以使用以下方式找到与所有用户类型相关联的用户GROUP BY

select user, 
       case when cnt = 3 then 'Owner' 
            when cnt = 2 then 'Worker' 
            when cnt = 1 then 'Contractor' 
       end as user_type_new 
  from (select user, count(distinct user_type) as cnt
          from your_table
       group by user)

推荐阅读