简体   繁体   English

如何查询表并按条件汇总某些列,而不是其他列?

[英]How to query table and sum up certain columns by criteria, but not others?

From a starting table, let's say:从一个起始表,让我们说:

A一个 B C C
1 1 1 1 99 99
2 2 2 2 88 88
3 3 3 3 77 77

I'm trying to write a query that would result in a table with a different value in column C based on the criteria that when A has value 2 , the value for C should be the existing value + the value from C where A is 1 .我正在尝试编写一个查询,该查询将根据以下条件在 C 2中生成一个具有不同1的表. Here's the result:结果如下:

A一个 B C C
1 1 1 1 99 99
2 2 2 2 187 187
3 3 3 3 77 77

Unsure if a grouping makes sense here, especially since there might be multiple similar criteria.不确定分组在这里是否有意义,尤其是因为可能有多个类似的标准。 The closes query I could think of would be我能想到的关闭查询是

SELECT A, B, C+(SELECT C FROM table1 WHERE A=1 LIMIT 1) FROM table1 WHERE A=2;

but this isn't valid SQL, since subqueries can't be used like this.但这不是有效的 SQL,因为不能像这样使用子查询。 Any suggestions are welcome, even if they involve somehow altering the structure of the original table.欢迎任何建议,即使它们涉及以某种方式改变原始表的结构。

consider below approach (tested in BigQuery)考虑以下方法(在 BigQuery 中测试)

select a, b, c + 
  case a 
    when 2 then sum(if(a = 1, c, 0)) over()
    else 0
  end c
from your_table      

if applied to sample data in your question - output is如果应用于您问题中的示例数据 - output 是

在此处输入图像描述

SELECT
    A,
    B,
    CASE
        WHEN A=2 THEN C + (SELECT C FROM table WHERE A = 1)
        ELSE C
    END AS C
FROM
    table;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM