如何按周计算列值的计数百分比?
How to calculate percentage by count of column values group by week?
我的 table 观点是这样的:
week ColB ColF
---------------------
45 1234 PART
45 8215 TEMP
45 2834 PART
45 4152 PART
45 5775 TEMP
45 6527 PART
45 1162 TEMP
45 9154
45 2162
46 4232 PART
46 3215 PART
46 5834 PART
46 6152 PART
46 7775 TEMP
46 8527 PART
46 9162 TEMP
46 2354
46 2562
46 9762
...
...
...
现在每周我需要做以下事情:
- 每周总共有多少
PART
和 TEMP
。我们称之为 total
。在 ColF
中,除了 PART
和 TEMP
之外,我还可以有其他值,例如空字符串或任何其他值。我只需要计算 PART
和 TEMP
。
- 每周有多少
TEMP
。我们称之为 temp
.
- 每个星期,除以
temp
/total
得到百分比。
所以输出应该是这样的。基本上按周列分组。
week ratio
---------------------
45 5.5%
46 4.3%
47 2.3%
48 1.7%
我是这样尝试的,但不知何故不完全理解如何实现上述结果?我的以下查询是错误的 -
select week, (SELECT week, count(*) FROM process WHERE ColF = 'TEMP' group by week) / count(*)
from process where ColF IN ('PART', 'TEMP')
group by week
order by week
这有可能做到吗?
您可以使用条件聚合。 avg()
可以方便地计算比率:
select week, avg(case when colf = 'TEMP' then 100.0 else 0 end) as ratio
from process
where colf in ('PART', 'TEMP')
group by week
我的 table 观点是这样的:
week ColB ColF
---------------------
45 1234 PART
45 8215 TEMP
45 2834 PART
45 4152 PART
45 5775 TEMP
45 6527 PART
45 1162 TEMP
45 9154
45 2162
46 4232 PART
46 3215 PART
46 5834 PART
46 6152 PART
46 7775 TEMP
46 8527 PART
46 9162 TEMP
46 2354
46 2562
46 9762
...
...
...
现在每周我需要做以下事情:
- 每周总共有多少
PART
和TEMP
。我们称之为total
。在ColF
中,除了PART
和TEMP
之外,我还可以有其他值,例如空字符串或任何其他值。我只需要计算PART
和TEMP
。 - 每周有多少
TEMP
。我们称之为temp
. - 每个星期,除以
temp
/total
得到百分比。
所以输出应该是这样的。基本上按周列分组。
week ratio
---------------------
45 5.5%
46 4.3%
47 2.3%
48 1.7%
我是这样尝试的,但不知何故不完全理解如何实现上述结果?我的以下查询是错误的 -
select week, (SELECT week, count(*) FROM process WHERE ColF = 'TEMP' group by week) / count(*)
from process where ColF IN ('PART', 'TEMP')
group by week
order by week
这有可能做到吗?
您可以使用条件聚合。 avg()
可以方便地计算比率:
select week, avg(case when colf = 'TEMP' then 100.0 else 0 end) as ratio
from process
where colf in ('PART', 'TEMP')
group by week