简体   繁体   English

按聚合条件对数据进行分组

[英]Grouping the data by aggregational condition

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.我需要编写一个查询(一个事务),它将元素分组并将元素的数据通过具有最小总和值的值的总和转换为组 - 例如 10。 If a value is equal to or greater of 10 it should be a separate group.如果一个值等于或大于 10,它应该是一个单独的组。

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: id 为 3 的元素可以与任何其他元素进行分组,但理想情况下是小于 10 的另一个值。此外,我需要在查询执行后更新元素和组之间的关系:

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?有任何想法吗?

You can use analytical function (for given sample data) as follows:您可以使用分析 function(对于给定的样本数据)如下:

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

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

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