Reference to the source of the blog: http://www.cnblogs.com/luhe/p/4155612.html, the blog has been modified to add, modified the wrong place
Previously used Row_number (), rank () and other sort with over (partition by ... Order by ...), both of which are better understood: group First, then rank within the group.
Today suddenly came across the sum (...) over (partition by ... Order by ...), actually do not clear how to carry out, so looked up some information, did the next real exercise.
1. From the simplest start
SUM (...) over (), sum all rows
SUM (...) over (order by ...), and = First line to sum all values of the last row of the same ordinal line as the current line, the text is not well understood, see the algorithm parsing.
With AAAs(SELECT1A1B3CFrom dualUnionSELECT2A2B3CFrom dualUnionSELECT3A3B3CFrom dualUnionSELECT4A4B3CFrom dualUnionSELECT5A5B3CFrom dualUnionSELECT6A5B3CFrom dualUnionSELECT7A2B3CFrom dualUnionSELECT8A2B8CFrom dualUnionSELECT9A 3 B, 3 C from dual) select A,b,c,sum (c ) over (order by b) sum1,-- Sort, sum all the values of column C of the order number of the current line sum (c) over () Sum2-- No sort, sum column C all values
From AA
Add by Pine door a flower:
- With AA as
- ( SELECT 1 A,1 B, 3 C from dual
- UNION
- SELECT 2 A,2 B, 3 C from dual
- UNION
- SELECT 3 A,3 B, 3 C from dual
- UNION
- SELECT 4 A,4 B, 3 C from dual
- UNION
- SELECT 5 A,5 B, 3 C from dual
- UNION
- SELECT 6 A,5 B, 3 C from dual
- UNION
- SELECT 7 A,2 B, 3 C from dual
- UNION
- SELECT 8 A,2 B, 8 C from dual
- UNION
- SELECT 9 A,3 B, 3 C from dual
- )
- SELECT A,
- B
- C
- SUM (c) over (order by a) sum1,--sorting, summing all values in column C of the order number of the current row--"New for bloggers"
- SUM (c) over (order by B) sum2,---have sort, sum all values in column C of the order number of the current row
- SUM (c) over () sum3 from AA order by A; --no sorting, sum column C all values
2. Combined with partition by
SUM (...) over (partition by ...), sum of rows in the same group
SUM (...) over (partition by ...), with the 1th sort summation principle, except that the scope is limited within the group
With AAAs(SELECT1A1B3CFrom dualUnionSELECT2A2B3CFrom dualUnionSELECT3A3B3CFrom dualUnionSELECT4A4B3CFrom dualUnionSELECT5A5B3CFrom dualUnionSELECT6A5B3CFrom dualUnionSELECT7A2B3CFrom dualUnionSELECT7A2B8CFrom dualUnionSELECT9A3B 3 C from dual) select a,b,c,sum (c) over (partition by b ) Partition_sum,sum (c) over (partition by b order by a desc) partition_order_sum from aa;
Db2--sum over partition by usage