0

i have user table which have 2 columns User and group , one user can have multiple groups

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

i am trying to write sql to convert above table data in below format.

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

Need help. Thanks

niting
  • 55
  • 4
  • 12

3 Answers3

0

I think you can do this with CASE and grouping:

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
kjmerf
  • 4,275
  • 3
  • 21
  • 29
  • 1
    That wasn't included in the example. Probably worth a follow up question to the OP instead of a down vote on an answer... – kjmerf Dec 20 '16 at 19:14
0

Try this:

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.: Avoid keywords like USER in your tables.

Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
  • This does not meet the requirement entirely - the OP's desired output shows `'No'` rather than `NULL` when the group is not found for that user. –  Dec 20 '16 at 19:06
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