简体   繁体   中英

Percentage of existence in a group in SQL

Hi I have a requirement of finding the occurrence percentage of specific items in a group. My table is like this

Team     Objective     Status
--------------------------------
Team1      Obj1          Submitted
Team1      Obj2          Stretch
Team1      Obj3          Submitted
Team1      Obj4          Submitted
Team1      Obj5          Stretch
Team1      Obj6          Submitted
Team1      Obj7          Submitted
Team2      Obj1          Stretch
Team2      Obj2          Submitted
Team2      Obj3          Submitted
Team2      Obj4          Stretch
Team2      Obj5          Stretch
Team2      Obj6          Stretch
Team2      Obj7          Submitted
Team2      Obj8          Submitted
-------------------------------------

And the required result set is like this

Team        Status        Percentage
-----------------------------------------
Team1     Submitted         71%
Team1     Stretch           28%
Team2     Submitted         50%
Team2     Stretch           50%
------------------------------------------------

Im having just a group query like this

select Team,status,count(*) from Objectives group by Team Status

Im not getting an idea how to calculate the percentage from the group

You can use OVER Clause.

SELECT
    Team,
    Status,
    COUNT(*) * 100 / SUM(COUNT(*)) OVER(PARTITION BY(Team)) AS Percentage
FROM Objectives 
GROUP BY Team, Status
ORDER BY Team, Status Desc

Try like using subquery

     Select b.team,b.status, (b.cnt/a.cnt )*100.00 
    from 
      (select Team,status,count(*) as cnt 
      from table_name group by Team, Status) b,
     (Select count(*)  as cnt from table_name) a

or you could write like below

      select Team,status,(count(*)/(select count(*) from table_name))*100.00
      as percentage 
      from table_name group by Team, Status

You can achieve this by using subquery as like the following-

 SELECT A.Team, A.Status, (A.STATUS_TOTAL / B.TEAM_TOTAL) * 100.00 Percentage
    FROM (  SELECT O.Team, O.Status, COUNT (*) STATUS_TOTAL
              FROM Objectives O
          GROUP BY O.Team, O.Status) A,
         (  SELECT O.Team, COUNT (*) TEAM_TOTAL
              FROM Objectives O
          GROUP BY O.Team) B
   WHERE A.Team = B.Team
ORDER BY A.Team, A.Status

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