【问题标题】:SUMIF case when SQL - sum based on row valueSQL 时的 SUMIF 情况 - 基于行值求和
【发布时间】:2021-08-31 18:40:53
【问题描述】:

我有一个包含列 A、B、C 的数据集。我想对 C 求和,其中 B 中的值 >= 比 B 中的其余值。我尝试了 Sum 的情况,但不能t 似乎获得了使用行值的条件。有什么想法吗?

输入:

A|B|C
1|1|1
1|2|1
1|3|1
2|1|0
2|2|1
2|3|0

想要的输出:

A|B|C|Output
1|1|1|3
1|2|1|2
1|3|1|1
2|1|0|1
2|2|1|1
2|3|0|0

代码已尝试,但由于条件原因无法正常工作

SUM(case when B>=B then C end) over(partition by A) as Output

输出计算:

A|B|C|Output calculation                                  |Excel calculation                | Output 
1|1|1|Sum all values in Col C where values in B>=1 and A=1 | =SUMIFS(C:C,B:B,">="&B2,A:A,A2) |=3
1|2|1|Sum all values in Col C where values in B>=2 and A=1 | =SUMIFS(C:C,B:B,">="&B3,A:A,A3) |=2
1|3|1|Sum all values in Col C where values in B>=3 and A=1 | =SUMIFS(C:C,B:B,">="&B4,A:A,A4) |=1
2|1|0|Sum all values in Col C if values in B>=1 and A=2    | =SUMIFS(C:C,B:B,">="&B5,A:A,A5) |=1
2|2|1|Sum all values in Col C if values in B>=2 and A=2    | =SUMIFS(C:C,B:B,">="&B6,A:A,A6) |=1
2|3|0|Sum all values in Col C if values in B>=3 and A=2    | =SUMIFS(C:C,B:B,">="&B7,A:A,A7) |=0

【问题讨论】:

  • 您使用的是 Bigquery 还是 T-SQL?我现在已经删除了冲突的标签
  • 什么是“其余值”? (对我来说)你的输出是如何计算的还不清楚。也许你可以展示一下这个细节。
  • “其余值” = col B 中的所有值
  • 已添加 excel 公式,可能有助于解释更多信息 - 希望对您有所帮助
  • @16143 "rest of the values" = col B 中的所有值,表示仅当 b = max(b) 时才计算 sum(c)

标签: sql google-bigquery sum case


【解决方案1】:

我认为您需要一个自联接或相关子查询:

select t.*,
       (select sum(t2.c)
        from t t2
        where t2.a = t.a and t2.b > t.b
       ) as output
from t;

您的逻辑可能相当于通过 b 值对 c 进行反向求和:

select t.*,
       sum(c) over (partition by a order by b desc)
from t;

但是,我不确定您希望如何处理具有相同 b 值的行。

【讨论】:

  • 顶部查询中的 t2 是什么?
  • @16143 - 如果相关子查询具有FROM t t2,则它是对表t 的第二次引用,给定别名t2,以便可以分别引用这两个实例。很像t AS t1 INNER JOIN t AS t2 的自连接(AS 是可选的,因此隐含在此答案的代码中)
  • 太棒了!谢谢!顶部查询中的 where caluse 让您可以控制我需要的条件。谢谢!
【解决方案2】:

考虑以下方法

select *,
  sum(c) over(partition by a order by b desc) output
from data    

如果应用于您问题中的样本数据 - 输出是

同时,我注意到与如何处理 B=B 情况有关的问题存在一些差异,在 excel 公式中它说 where values in B>... 而在输出示例和代码中尝试它是 when B>=B then 到目前为止,这就是全部当前提供的答案可以。
所以,下面“做”B>B 逻辑(并且可以很容易地修改为任何滞后值)

select *,
  sum(c) over(partition by a order by b range between 1 following and unbounded following) output
from data    

有输出

【讨论】:

    【解决方案3】:
    select * , sum(C) over (partition by A order by B desc)
    from data
    order by A,B
    
    一个 |乙 | c |和 -: | -: | -: | --: 1 | 1 | 1 | 3 1 | 2 | 1 | 2 1 | 3 | 1 | 1 2 | 1 | 0 | 1 2 | 2 | 1 | 1 2 | 3 | 0 | 0

    db小提琴here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多