我得到了一条 SQL 语句:
Select
ID, GroupID, Profit
From table
我现在想添加第四列的集团利润百分比。因此,查询应将同一组 ID 的所有利润相加,然后将该数字除以唯一 ID 的利润。
有没有办法做到这一点?常规的 sum 函数似乎不能解决问题。
谢谢
select t1.ID,
t1. GroupID,
(t1.Profit * 1.0) / t2.grp_profit as percentage_profit
from table t1
inner join
(
select GroupID, sum(Profit) as grp_profit
from table
group by GroupID
) t2 on t1.groupid = t2.groupid
具有窗口功能的另一种选择
select ID, GroupID, Profit * 1. / SUM(profit) OVER(PARTITION BY GroupID)
from t1
使用标量子查询的替代解决方案如下:
select t1.ID, t1.GroupID, (select sum(t2.Profit) * 1.0 / t1.Profit
from table t2
where t2.GroupID = t1.GroupID) as percentage_profit
from table t1;
要提供替代答案,尽管效率较低,但要使用标量子查询。
SELECT ID, GroupId, Profit, (Profit/(SELECT sum(Profit)
FROM my_table
WHERE GroupId= mt.GroupId))*100 as pct
FROM my_table as mt
从它的阅读方式来看,我不确定您是想要“集团利润百分比”还是您想要 group_profit / 个人利润
这就是听起来的方式“因此,查询应该将同一组 ID 的所有利润相加,然后将该数字除以唯一 ID 的利润”
无论哪种方式,只需将除数切换为您想要的!
此外,如果您使用Postgresql
>= 8.4,则可以使用窗口函数。
SELECT ID, GroupId, Profit, (Profit/ (sum(Profit) OVER(partition by GroupId)))*100 as pct
FROM core_dev.my_table as mt