Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query - Sum with Conditions in Partition Clause?

Tags:

sql

sql-server

Suppose I had this following table in SQL Server:

ColA     ColB     ColC
A        1        100
A        0        -100
A        1        -100
A        0        100
A        1        100
A        1        -100
B        1        200
B        1        -200
B        1        200
C        0        300
C        1        -300

And what I was looking to achieve (in words) woud be: Create a new column, Conditional_Sum = Sum of ColC for each value in ColA where ColB = 1 and ColC > 0

So, the final result would be (added in RowNum to show how I got the values):

Rownum     ColA     ColB     ColC      Conditional_Sum
1          A        1        100       200             (rows 1+5)
2          A        0        -100      200             (rows 1+5)
3          A        1        -100      200             (rows 1+5)
4          A        0        100       200             (rows 1+5)
5          A        1        100       200             (rows 1+5)
6          A        1        -100      200             (rows 1+5)
7          B        1        200       400             (rows 7+9)
8          B        1        -200      400             (rows 7+9)
9          B        1        200       400             (rows 7+9)
10         C        0        300       0               (no rows match)
11         C        1        -300      0               (no rows match)

So, my pseudo-SQL for this would be:

Sum(ColC) Over(Partition By ColA, ColB=1,ColC>0) as Conditional_Sum

How can I achieve this kind of result in my dataset??

Thanks!!!!!!

like image 871
John Bustos Avatar asked Aug 29 '13 16:08

John Bustos


People also ask

Can we use aggregate function in partition by?

We can use the SQL PARTITION BY clause with the OVER clause to specify the column on which we need to perform aggregation. In the previous example, we used Group By with CustomerCity column and calculated average, minimum and maximum values.

Can we use SUM function in where clause?

SQL SUM() with where clause We can selectively find the sum of only those rows, which satisfy the given condition. To do this, we can use the where clause in the SQL statement.

Can we use where clause in partition by Oracle?

For range- and list-partitioned data, as an alternative to this clause, you can specify a condition in the WHERE clause that restricts the retrieval to one or more partitions of table. Oracle Database will interpret the condition and fetch data from only those partitions.


1 Answers

Try this:

Sum(case when ColB = 1 and ColC > 0 then ColC else 0 end) over(partition by ColA)

My answer assumes that the conditional sum for rows 7 to 9 is supposed to be 400.

like image 94
Daniel Hilgarth Avatar answered Nov 15 '22 15:11

Daniel Hilgarth