简体   繁体   中英

MySQL - Group by two Columns

I have a table that looks like this

id, user_id   , type, date
3,  ivnWvOQqoN, iOS , 2015-11-24 15:46:09
4,  dskIbJhuSd, iOS , 2015-11-23 19:39:31
5,  dskIbJhuSd, iOS , 2015-11-24 23:37:45
6,  ----------, iOS , 2015-11-22 23:38:05
7,  ----------, iOS , 2015-11-23 23:38:10

And right now I am doing a query like this

SELECT COUNT(*) AS entries, user_id, DATE(created_at) as date, device_type
FROM App_Usage
WHERE device_type = 'iOS'
  AND created_at between 2015-11-22 AND 2015-11-25
GROUP BY DATE(created_at), user_id

This return results that I would expect it looks like this

((1L, '----------', datetime.date(2015, 11, 22), 'ios'),
(1L, 'dskIbJhuSd', datetime.date(2015, 11, 23), 'ios'),
(1L, '----------', datetime.date(2015, 11, 23), 'ios'),
(1L, 'dskIbJhuSd', datetime.date(2015, 11, 24), 'ios'),
(1L, 'ivnWvOQqoN', datetime.date(2015, 11, 24), 'ios')

The last two lines in the above code, become the last line in the next code. And the second line in above code becomes 2nd line in code below.

My question is could I group by date and if the user is not '----------' , so it would return a result like this

((1L, '----------', datetime.date(2015, 11, 22), 'ios'),
(1L, 'combo of users' datetime.date(2015, 11, 23), 'ios'),
(1L, '----------', datetime.date(2015, 11, 23), 'ios'),
(2L, 'combo of users', datetime.date(2015, 11, 24), 'ios'),

I left the user_id in the first results to show that as long as the user is '---------' I want those grouped and the others grouped.

So I want to group by date, and then by where user is not '----------' , how could I do this or is it even possible?

DESIRED OUTPUT

OUTPUT:

number of uses, user_id**, type, date;
(1, '----------', 'ios', '2015-11-22 23:38:05'),
(1, 'some users or combo', 'ios', '2015-11-22 13:33:33'),
(2, 'some users or combo', 'ios', '2015-11-23 13:35:37'),
(1, '----------', 'ios', '2015-11-24 00:09:44'),
(2, 'some users or combo', 'ios', '2015-11-24 00:09:44'),

**So I want any users that is '----------' to be grouped with '-------' but any user that is not '--------' to be goruped with all other users. As you can see on the 24rd, the 2 different uses are put as one and the use that was '-------' is serperate (this is the last two lines above)

select count(*) as entries, dateCreate, device_type, user_id
from 
    (SELECT DATE(created_at) as dateCreate, device_type, case when user_id = '----------' then '-----------' else 'combo of users' as user_id  
    FROM App_Usage 
    WHERE device_type = 'iOS' 
    AND created_at between 2015-11-22 
    AND 2015-11-25) as temp_table 
GROUP BY dateCreate, user_id, device_type

note: used dateCreate instead of date as it is a keyword

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM