简体   繁体   中英

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

From a starting table, let's say:

A B C
1 1 99
2 2 88
3 3 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 . Here's the result:

A B C
1 1 99
2 2 187
3 3 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. Any suggestions are welcome, even if they involve somehow altering the structure of the original table.

consider below approach (tested in 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

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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