Oracle SQL查询垂直于水平与大小写

时间:2016-12-20 18:43:14

标签: sql oracle pivot

我的用户表有2列用户和组,一个用户可以有多个组

User  | Group
--------------
User1 | Group1
User1 | Group2
User2 | Group1
User2 | Group2
User3 | Group1
User4 | Group2

我正在尝试编写sql以下面的格式转换上面的表数据。

User    | Group1        | Group2
---------------------------------
User1   |   Yes         |   Yes
User2   |   Yes         |   Yes
User3   |   Yes         |   No
User4   |   No          |   Yes

需要帮助。 感谢

3 个答案:

答案 0 :(得分:0)

我认为你可以用CASE和分组来做到这一点:

SELECT user,
CASE WHEN MIN(`group`) = 'Group1' THEN 'Yes' ELSE 'No' END AS Group1,
CASE WHEN MAX(`group`) = 'Group2' THEN 'Yes' ELSE 'No' END AS Group2
FROM t
GROUP BY user

答案 1 :(得分:0)

试试这个:

select usr,
max(case when grp = 'Group1' then 'Yes' else 'No' end) grp1,
max(case when grp = 'Group2' then 'Yes' else 'No' end) grp2
from table
group by usr;

P.S。:在表格中避免使用USER等关键字。

答案 2 :(得分:0)

with
     test_data ( usr , grp ) as (
       select 'User1', 'Group1' from dual union all
       select 'User1', 'Group2' from dual union all
       select 'User2', 'Group1' from dual union all
       select 'User2', 'Group2' from dual union all
       select 'User3', 'Group1' from dual union all
       select 'User4', 'Group2' from dual
     )
-- end of test data; the query begins below this line
select   usr,
         case when count(case when grp = 'Group1' then 1 end) > 0 
              then 'Yes' else 'No' end as grp1,
         case when count(case when grp = 'Group2' then 1 end) > 0 
              then 'Yes' else 'No' end as grp2
from     test_data
group by usr
order by usr    --   order by is optional
;

USR    GRP1  GRP2
-----  ----  ----
User1  Yes   Yes
User2  Yes   Yes
User3  Yes   No
User4  No    Yes