简体   繁体   中英

Get data based on condition in oracle sql

My table

loads(Unique)       Value
 T123                11
 T234               9.5
 T456               15
 T678               35
 T345               3.7    

Want I want

 count(values<=10)    count(values>10 &<=20)   count(values>20) 
            2                       2                    1

I tried to use CASE but don't know the usage

CASE yes; not with COUNT but with SUM :

SQL> with test (loads, value) as
  2    (select 't123', 11   from dual union all
  3     select 't234',  9.5 from dual union all
  4     select 't456', 15   from dual union all
  5     select 't678', 35   from dual union all
  6     select 't345',  3.7 from dual
  7    )
  8  select
  9    sum(case when value <= 10 then 1 end) cnt_1,
 10    sum(case when value > 10  and value <= 20 then 1 end) cnt_2,
 11    sum(case when value > 20 then 1 end) cnt_3
 12  from test;

     CNT_1      CNT_2      CNT_3
---------- ---------- ----------
         2          2          1

SQL>

Use conditional aggregation as

select coalesce(sum(case when value<=10 then 1 end),0) as "values<=10",
       coalesce(sum(case when value>10 and value<=20 then 1 end),0) as "values>10value<20",
       coalesce(sum(case when value>20 then 1 end),0) as "values>20"
from your_table;

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