选择具有特定文本的行进行计数和求和
Selecting rows with specific text to count and sum
我需要按年份确定特定值的百分比。
数据集的值如下:
Year Col Value
2012 -20 p, 12
2012 -20 points, d 20
2012 -20 points, by 24
2012 -20 p, new 32
2012 -30 p, 1256
2012 -30 points, d 32
2012 -30 points, by 42
2012 -30 p, new 164
还有其他年份,但我只选择了 2012 年作为示例。
对于每一年,我想确定百分比为:
- 文本中包含
points
个单词的值的计数
除以 - 20
开头的值
与 30 的情况相同。
2012 年 -20 的预期产出:
(20+24)/(12+20+24+32)
我试过如下
Select year,
Col,
Count(0) as Value
, 100*count(0)/sum(count(case when Col like ‘-20%points%’ then 1 end) over (partition by year, substr(Col, 1,2))) as pct_20
/* Same for 40 poin
ts */
From table1
Where /* conditions */
Group by 1,2
但是我得到了不能嵌套有序分析函数的错误。
您只能在 OLAP 函数中嵌套聚合,反之则不行:
, 100*count(*)/NULLIF(sum(count(case when Col like ‘-20%points%’ then 1 end))
over (partition by year, substr(Col, 1,2)), 0) as pct_20
我想你想要条件聚合:
select year, substr(col, 1, 2),
sum(case when col like '%points%' then value end) / sum(value)
from t
group by 1, 2;
根据您的评论:
select year, substr(col, 1, 2),
sum(case when col like '%points%' then 1.0 end) / count(*)
from t
group by 1, 2;
我需要按年份确定特定值的百分比。
数据集的值如下:
Year Col Value
2012 -20 p, 12
2012 -20 points, d 20
2012 -20 points, by 24
2012 -20 p, new 32
2012 -30 p, 1256
2012 -30 points, d 32
2012 -30 points, by 42
2012 -30 p, new 164
还有其他年份,但我只选择了 2012 年作为示例。 对于每一年,我想确定百分比为:
- 文本中包含
points
个单词的值的计数
除以 - 20
与 30 的情况相同。 2012 年 -20 的预期产出:
(20+24)/(12+20+24+32)
我试过如下
Select year,
Col,
Count(0) as Value
, 100*count(0)/sum(count(case when Col like ‘-20%points%’ then 1 end) over (partition by year, substr(Col, 1,2))) as pct_20
/* Same for 40 poin
ts */
From table1
Where /* conditions */
Group by 1,2
但是我得到了不能嵌套有序分析函数的错误。
您只能在 OLAP 函数中嵌套聚合,反之则不行:
, 100*count(*)/NULLIF(sum(count(case when Col like ‘-20%points%’ then 1 end))
over (partition by year, substr(Col, 1,2)), 0) as pct_20
我想你想要条件聚合:
select year, substr(col, 1, 2),
sum(case when col like '%points%' then value end) / sum(value)
from t
group by 1, 2;
根据您的评论:
select year, substr(col, 1, 2),
sum(case when col like '%points%' then 1.0 end) / count(*)
from t
group by 1, 2;