Sql 基于子组中的几列计算百分比
我有一张表(我们称之为Sql 基于子组中的几列计算百分比,sql,sql-server,Sql,Sql Server,我有一张表(我们称之为表a),如下所示: ID Device Clicks 1 A 10 1 B 10 2 A 1 2 C 19 ID Device Clicks Percentage 1 A 10 50
表a
),如下所示:
ID Device Clicks
1 A 10
1 B 10
2 A 1
2 C 19
ID Device Clicks Percentage
1 A 10 50
1 B 10 50
2 A 1 5
2 C 19 95
我想从上面的a
构建一个表(我们称之为table B
),如下所示:
ID Device Clicks
1 A 10
1 B 10
2 A 1
2 C 19
ID Device Clicks Percentage
1 A 10 50
1 B 10 50
2 A 1 5
2 C 19 95
再次从表B
,我想导出表C
,其中每个ID
的更新设备
列将携带设备
列中的名称,前提是百分比
大于95%。如果每个ID
的Devices
之间的分割百分比是其他的,我们只需将UpdatedDevice
设置为Others
。例如,使用表B
中的数据,我们将得到表C
,如下所示:
ID Device Clicks Percentage UpdatedDevice
1 A 10 50 Others
1 B 10 50 Others
2 A 1 5 C
2 C 19 95 C
我想知道是否有一种方法可以一次性使用高级SQL窗口/分析函数,而不是生成中间表
select
Id
, Device
, Clicks
, Percentage
, UpdatedDevice = isnull(max(UpdatedDevice) over (partition by Id),'Others')
from (
select *
, Percentage = convert(int,(clicks / sum(clicks+.0) over (partition by Id))*100)
, UpdatedDevice = case
when (clicks / sum(clicks+.0) over (partition by Id)) >= .95
then Device
end
from t
) as cte
测试设置:
返回:
+----+--------+--------+------------+---------------+
| Id | Device | Clicks | Percentage | UpdatedDevice |
+----+--------+--------+------------+---------------+
| 1 | A | 10 | 50 | Others |
| 1 | B | 10 | 50 | Others |
| 2 | A | 1 | 5 | C |
| 2 | C | 19 | 95 | C |
+----+--------+--------+------------+---------------+
仅为了好玩,您可以不使用子查询执行此操作:
select t.*,
clicks * 1.0 / sum(clicks) over (partition by id) as ratio, -- you an convert to a percentage
(case when max(clicks) over (partition by id) >= 0.95 * sum(clicks) over (partition by device)
then first_value(device) over (partition by id order by clicks desc)
else 'Others'
end) as UpdatedDevice
from t;
计算
UpdatedDevice
的关键思想是,最大值将是满足95%规则的设备。当然还有first\u value()
。非常感谢您提供了一个非常容易理解的查询和正确的解决方案@user1330974很乐意帮忙!非常感谢。在没有任何子查询的情况下为我的案例学习解决方案是很酷的。:)