SQL查询-子样本的百分比

SQL查询-子样本的百分比,sql,sum,Sql,Sum,我得到了一个SQL语句: Select ID, GroupID, Profit From table 现在,我想在第四栏添加集团利润的百分比。 因此,查询应将同一组id的所有利润相加,然后将该数字除以唯一id的利润 有办法做到这一点吗?正则和函数似乎不起作用 谢谢使用标量子查询的替代解决方案如下: select t1.ID, t1.GroupID, (select sum(t2.Profit) * 1.0 / t1.Profit from

我得到了一个SQL语句:

Select
ID, GroupID, Profit
From table
现在,我想在第四栏添加集团利润的百分比。 因此,查询应将同一组id的所有利润相加,然后将该数字除以唯一id的利润

有办法做到这一点吗?正则和函数似乎不起作用


谢谢

使用标量子查询的替代解决方案如下:

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 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 * 1. / SUM(profit) OVER(PARTITION BY GroupID)
from t1

还有一个窗口功能选项

select ID, GroupID, Profit * 1. / SUM(profit) OVER(PARTITION BY GroupID)
from t1

要提供另一种答案(尽管效率较低),可以使用标量子查询

SELECT  ID, GroupId, Profit, (Profit/(SELECT sum(Profit) 
                                     FROM my_table 
                                     WHERE GroupId= mt.GroupId))*100 as pct
FROM my_table as mt
从阅读的方式来看,我不确定你是想要“集团利润百分比”,还是想要集团利润/个人利润

这听起来就是“因此,查询应该对同一组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

要提供另一种答案(尽管效率较低),可以使用标量子查询

SELECT  ID, GroupId, Profit, (Profit/(SELECT sum(Profit) 
                                     FROM my_table 
                                     WHERE GroupId= mt.GroupId))*100 as pct
FROM my_table as mt
从阅读的方式来看,我不确定你是想要“集团利润百分比”,还是想要集团利润/个人利润

这听起来就是“因此,查询应该对同一组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
这是MySQL吗?(大多数其他RDBMS都有可用于处理此问题的窗口函数,但MySQL没有)这是MySQL吗?(大多数其他RDBMS都有可用于处理此问题的窗口函数,但MySQL没有。)