【问题标题】:Divide the column by the sum grouped by another column将该列除以由另一列分组的总和
【发布时间】:2021-08-07 20:05:01
【问题描述】:

我有一张这样的桌子

source   |  destination   | frequency
-------------------------------------
   a     |       b        |     4
   a     |       c        |     2
   b     |       c        |     1
   b     |       a        |     3

我想将frequency 除以frequencysource 的总和。因此,我正在寻找这样的表

source   |  destination   | frequency
-------------------------------------
   a     |       b        |     4/6
   a     |       c        |     2/6
   b     |       c        |     1/4
   b     |       a        |     3/4

有没有办法在单个 sql 查询中做到这一点?

【问题讨论】:

  • 您能否创建一个新字段来计算每行的总和 - 然后只需按“源”对组进行简单除法?这可能不是单一的查询方法,而是最初的想法
  • 用您正在使用的数据库标记您的问题。

标签: sql postgresql group-by count sum


【解决方案1】:

您可以使用SUM()窗口函数。

如果你想要一个数字结果:

SELECT source, destination,
       frequency / SUM(frequency) OVER(PARTITION BY source)
FROM tablename

根据您的数据库,如果它执行整数之间的整数除法,您可能需要乘以 1.0:

SELECT source, destination,
       1.0 * frequency / SUM(frequency) OVER(PARTITION BY source)
FROM tablename

如果您希望将结果作为字符串,您可以使用连接来实现:

SELECT source, destination,
       CONCAT(frequency, '/', SUM(frequency) OVER(PARTITION BY source))
FROM tablename

我使用了CONCAT(),但如果您的数据库不支持它,请使用其连接运算符,并且您可能需要将整数值转换为字符串。

【讨论】:

    【解决方案2】:

    对于单个查询,您可以使用join

    select t.source, t.destination, t.frequency/sum(t1.frequency) from testtable t join testtable t1 on t1.source = t.source group by t.source, t.destination
    

    【讨论】:

      【解决方案3】:

      您可以使用sum over

      select *, frequency /  Sum(frequency) over(partition by source)  
      from table
      

      如果frequencyint,则乘以1.0 或cast/convert 得到十进制结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-20
        • 2017-03-25
        • 2020-12-06
        • 1970-01-01
        相关资源
        最近更新 更多