SQL中组中存在的百分比

时间:2019-06-27 05:56:05

标签: sql

您好,我需要找到一组中特定项目的出现百分比。我的桌子是这样的

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
-------------------------------------

所需的结果集是这样的

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

我只有这样的组查询

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

我不知道如何计算组中的百分比

3 个答案:

答案 0 :(得分:2)

您可以使用OVER条款。

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

答案 1 :(得分:1)

尝试使用子查询

     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

或者您可以像下面这样写

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

答案 2 :(得分:0)

您可以通过使用如下所示的子查询来实现此目的-

 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