简体   繁体   中英

Oracle query Group by 3 values

I have a query that returns 3 columns with USERNAME, LAST_LOGIN and DAYS_FROM LOGIN.

USERNAME    LAST_LOGIN          DAYS_FROM_LOGIN
ASUNI_O     2020-06-04T14:37:58 8
BUNHU_T     2020-06-10T13:55:02 2
CHET_RA     2020-05-19T13:34:22 24
CHHANA_H    
CRAWFO_R    2020-06-08T09:46:53 4
DAVEL_M     2020-06-11T14:17:36 1
Dagama_E    2020-06-11T12:14:10 1
Dewet_Se    
Dillon_A    2020-06-11T11:47:55 1

What I would like to do is group these by into 3 groups, less than 14 days, more than 14 days and never logged in

Might look something like this

Count   User_Activity
    6   less_than_14
    1   More_than_14
    2   Never_logged_in

I was thinking of 3 nested queries each one providing the details of each group.

You can use the SIGN function as follows:

SELECT CASE
            WHEN SIGN(DAYS_FROM_LOGIN - 14) = - 1 THEN
                'less_than_14'
            WHEN SIGN(DAYS_FROM_LOGIN - 14) = 1  THEN
                'more_than_14'
            ELSE 'Never_logged_in'
       END AS USER_ACTIVITY,
       COUNT(1) AS USER_ACTIVITY
  FROM YOUR_TABLE
 GROUP BY SIGN(DAYS_FROM_LOGIN - 14);

You can do with case expression as following. here is the db<>fiddle

select
  count(*) as count,
  subq.user_activity
from
(
  select
    case 
      when days_from_login < 14 then 'less_than_14'
      when days_from_login > 14 then 'more_than_14'
      else 'Never_logged_in'
    end as user_activity
  from yourTable
) subq
group by
  subq.user_activity

output:

*---------------------*
| COUNT USER_ACTIVITY |
*---------------------*
  1     more_than_14
  2     Never_logged_in
  6     less_than_14
*---------------------*
select count(*) count,user_activity
from
(select case when DAYS_FROM_LOGIN >14 then 'More than 14'
             when DAYS_FROM_LOGIN <14 then 'Less than 14'
             when DAYS_FROM_LOGIN IS NULL then 'Never Logged In'
        end as User_activity
from 
table1) 
group by user_activity

sqlfiddle

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