oracle 需要按ID的计数进行分组,同时获取不按分组的总计数

mdfafbf1  于 2023-02-07  发布在  Oracle
关注(0)|答案(3)|浏览(237)

需要按ID的计数进行分组,同时获得没有按以下项分组的计数总数,这样我就可以获得ID的总计数,并检查按类别分组的每个组占总计数的百分比。
--用于oracle sql脚本
以下是我目前拥有的东西:

SELECT
    count(id) as unit_count,
    category
FROM sales
GROUP BY category
ORDER BY count(id) DESC;

SELECT
    count(id) as total_count
FROM sales

我不知道如何将上述两者结合起来
我寻找的最终结果如下所示:
| 范畴|计数|占总数的百分比|
| - ------|- ------|- ------|
| 电视机|一百|百分之二十五|
| 移动的电话|三百|75%|

a2mppw5e

a2mppw5e1#

窗口函数在聚合之后计算。这意味着SUM(COUNT(*)) OVER ()将对整个结果集的计数求和...

SELECT
    category,
    count(id) as unit_count,
    COUNT(*) / SUM(COUNT(*)) OVER () AS percentage_of_all_units
FROM sales
GROUP BY category
ORDER BY count(id) DESC;
pkln4tw6

pkln4tw62#

下面是根据所提到的场景的示例表:

create table sales(id number(3),
category    varchar2(20))
/

insert all
into sales values('01','televisions')
into sales values('02','televisions')
into sales values('03','televisions')
into sales values('04','televisions')
into sales values('05','televisions')
into sales values('06','televisions')
into sales values('07','mobile phones')
into sales values('08','televisions')
into sales values('09','mobile phones')
into sales values('10','mobile phones')
into sales values('11','televisions')
into sales values('12','televisions')
select * from dual;
/
select * from sales;
/
-- Required Query --
select category,count(*) count,
(count(*) / (select count(*) from sales) * 100)||'%' percentage_of_total
from sales
group by category;
vngu2lb8

vngu2lb83#

我没有您的表或数据,所以下面的示例基于Scott的示例模式。
emp表中的行数:

SQL> select count(*) from emp;

  COUNT(*)
----------
        14

每项工作的雇员人数:

SQL> select job,
  2    count(*) cnt
  3  from emp
  4  group by job
  5  order by cnt desc;

JOB              CNT
--------- ----------
CLERK              4
SALESMAN           4
MANAGER            3
ANALYST            2
PRESIDENT          1

组合(即您的要求):

SQL> select job,
  2    count(*) cnt,
  3    round((count(*) / (select count(*) from emp) * 100), 0) pct
  4  from emp
  5  group by job
  6  order by cnt desc;

JOB              CNT        PCT
--------- ---------- ----------
CLERK              4         29
SALESMAN           4         29
MANAGER            3         21
ANALYST            2         14
PRESIDENT          1          7

SQL>

或者,如@Mat所建议的,第3行可能是

round((count(*) / sum(count(*)) over () * 100), 0) pct

适用于您的案例:

select category,
  count(*) as unit_count,
  round((count(*) / (select count(*) from sales) * 100), 0) percentage_of_total,
  --
  round((count(*) / sum(count(*)) over () * 100), 0) percentage_of_total_2
from sales
group by category
order by unit_count desc;

相关问题