mysql—每行除以两列值相同的行之和

wbgh16ku  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(291)

我想计算每一行的除法,即所有具有相同dateadded和fundid的行的总和,但是我的查询似乎是错误的,因为结果不是我所期望的。我的表架构如下所示,我避开了我的表架构,因为它有更多的列:

+----+--------+------------+--------+
| id | fundid | Dateadded  | amount |
+====+========+============+========+
| 1  |  45    | 21-02-2018 |  5412  |
| 2  |  45    | 21-02-2018 |  5414  |
| 3  |  45    | 21-02-2018 |  1412  |
| 4  |  45    | 22-02-2018 |  5756  |
| 5  |  45    | 22-02-2018 |  4412  |
| 6  |  45    | 25-02-2018 |  2532  |
| 7  |  45    | 26-02-2018 |  7892  |
| 8  |  45    | 26-02-2018 |  8143  |
+----+-------+-------------+--------+

id为1、2、3的行应一起计算,因为它们具有相同的fundid和日期。
id为4,5的行相同。
id为6的行仅为一行。
id为7,8的行是一样的。
我的sql查询:

SELECT fundid
     , Dateadded
     , ( amount / SUM(amount) ) AS AvgRow 
  FROM stock2 
 GROUP 
    BY fundid
     , Dateadded 
 ORDER 
    BY DateAdded ASC
xqkwcwgp

xqkwcwgp1#

查看一个解释得很好的回复,该回复涉及到使用group byhere)的类似问题。
与这里描述的情况类似,因为您的查询是不明确的:每行应该使用什么“amount”。i、 e.如果您尝试:

SELECT fundid, Dateadded, ( AVG(amount) / SUM(amount) ) AS AvgRow FROM stock2 GROUP BY fundid, Dateadded ORDER BY DateAdded ASC

它将工作,因为平均(金额)是不含糊不清的每一对(基金会,dateadded)应该一起计算。
你似乎在寻找这样的东西:

SELECT st.fundid, st.Dateadded, ( amount / st2.total) ) AS AvgRow 
   FROM stock2 st 
   inner join 
      (select fundid, Dateadded, sum(amount) as total
       from stock2
       GROUP BY fundid, Dateadded) st2 
   on st.fundid = st2.fundid and st.Dateadded = st2.Dateadded
   order by st.Dateadded
tvokkenx

tvokkenx2#

这就是你想要的吗?

select t.*, t.amount / tt.total_amount
from stock2  t join
     (select fundid, dateadded, sum(amount) as total_amount
      from stock2 t
      group by fundid, dateadded
     ) tt
     using (fundid, dateadded);

还是这个?

select fundid, dateadded, sum(t.amount) / tt.total_amount
from stock2  t cross join
     (select sum(amount) as total_amount
      from stock2 t
     ) tt
 group by fundid, dateadded, tt.total_amount;

相关问题