Reputation: 55
I need to compose a query (one transaction) that will group elements and transform element's data into groups by sum of values with minimum sum value - 10 for example. If a value is equal to or greater of 10 it should be a separate group.
ElementId | GroupId | Value
1 | NULL | 12
2 | NULL | 10
3 | NULL | 9
4 | NULL | 13
5 | NULL | 25
GroupId | Sum
empty
Element with id 3 can be grouped with any other element, but ideally with another value that fewer than 10. Also, I need to update the relationship between elements and groups After the query execution:
ElementId | GroupId | Value
1 | 1 | 12
2 | 2 | 10
3 | 3 | 9
4 | 3 | 13
5 | 4 | 25
GroupId | Sum
1 | 12
2 | 10
3 | 22 (13 + 9)
4 | 25
Any ideas?
Upvotes: 0
Views: 28
Reputation: 35900
You can use analytical function (for given sample data) as follows:
Select groupid_new as groupid,
Sum(value) as value
From
(Select t.*,
Sum(case when value >= 10 then value end) over (order by elementid) as groupid_new
From your_table t) t
Group by groupid_new
Upvotes: 2