Oracle sql to count instances of different values in single column

前端 未结 2 926
自闭症患者
自闭症患者 2020-12-04 00:48

I have a table with status column. I want an Oracle sql query which will list me count of rows in each status in only one row. for eg if my table is

Table A
         


        
相关标签:
2条回答
  • 2020-12-04 00:55

    If you are using Oracle 11g, then you can use the PIVOT function:

    select *
    from
    (
      select tkey, status, 
        status as col
      from tableB b
      left join tableA a
        on a.fkey = b.fkey
    ) src
    pivot
    (
      count(status)
      for col in ('20' as Count_Status20, 
                  '30' as Count_Status30,
                  '40' as Count_Status40)
    ) piv;
    

    See SQL Fiddle with Demo

    If you are not using Oracle11g, then you can use an aggregate function with a CASE statement:

    select tkey, 
      count(case when status = 20 then 1 else null end) as Count_Status20,
      count(case when status = 30 then 1 else null end) as Count_Status30,
      count(case when status = 40 then 1 else null end) as Count_Status40
    from tableB b
    left join tableA a
      on b.fkey = a.fkey
    group by tkey
    

    See SQL Fiddle with Demo

    0 讨论(0)
  • 2020-12-04 01:09
    select fkey,
           sum(case when status = 20 then 1 else 0 end) as count_status20,
           sum(case when status = 30 then 1 else 0 end) as count_status30,
           sum(case when status = 40 then 1 else 0 end) as count_status40,
    from your_table
    group by fkey
    
    0 讨论(0)
提交回复
热议问题