SQL multiple rows into one

2019-08-10 07:30发布

问题:

It seems like an easy task, but i can't seem to wrap my head around it.

I just need to find out, users, that used mobiles, users that used desktop and users that used both, on day to day basis. Every user/access_dt combination should result only 1 row.

Example data is following:

USER, ACCESS_DATE, FORMFACTOR
   1   01-01-2014      Mobile
   1   01-01-2014      Desktop
   2   01-01-2014      Mobile
   3   01-01-2014      Desktop

Desired output:

USER, ACCESS_DATE, KEY_MOBILE, KEY_DESKTOP, KEY_MOBILE_DESKTOP
   1   01-01-2014           1            1                   1
   2   01-01-2014           1            0                   0
   3   01-01-2014           0            1                   0

Thank you very much!

回答1:

This is a pivot query, basically. I would do it with conditional aggregation:

select user, access_date,
       max(case when FORMFACTOR = 'Mobile' then 1 else 0 end) as KEY_MOBILE,
       max(case when FORMFACTOR = 'Desktop' then 1 else 0 end) as KEY_DESKTOP,
       (case when max(case when FORMFACTOR = 'Mobile' then 1 else 0 end)  > 0 and
                  max(case when FORMFACTOR = 'Desktop' then 1 else 0 end) > 0
             then 1 else 0
        end) as KEY_MOBILE_DESKTOP
from table t
group by user, access_date;