不能在同一个查询中反复使用group(partition by)?

use*_*405 15 sql db2 group-by partition-by

我有一个myTable有3列的表.col_1是一个INTEGER和另外两列是DOUBLE.例如,col_1={1, 2}, col_2={0.1, 0.2, 0.3}.in中的每个元素col_1都包含所有值,col_2并且col_2每个元素都有重复的值col_1.第3列可以具有任何值,如下所示:

    col_1 | col_2 | Value
    ----------------------
    1     |  0.1  |  1.0
    1     |  0.2  |  2.0
    1     |  0.2  |  3.0
    1     |  0.3  |  4.0
    1     |  0.3  |  5.0
    2     |  0.1  |  6.0
    2     |  0.1  |  7.0
    2     |  0.1  |  8.0
    2     |  0.2  |  9.0
    2     |  0.3  |  10.0
Run Code Online (Sandbox Code Playgroud)

我想要的是SUM()Value列分区上使用聚合函数col_1并按其分组col_2.上表应如下所示:

    col_1 | col_2 | sum_value
    ----------------------
    1     |  0.1  |  1.0
    1     |  0.2  |  5.0
    1     |  0.3  |  9.0
    2     |  0.1  |  21.0
    2     |  0.2  |  9.0
    2     |  0.3  |  10.0
Run Code Online (Sandbox Code Playgroud)

我尝试了以下SQL查询:

SELECT col_1, col_2, sum(Value) over(partition by col_1) as sum_value
from myTable
GROUP BY col_1, col_2
Run Code Online (Sandbox Code Playgroud)

但是在DB2 v10.5上,它给出了以下错误:

SQL0119N  An expression starting with "Value" specified in a SELECT 
clause, HAVING clause, or ORDER BY clause is not specified in the 
GROUP BY clause or it is in a SELECT clause, HAVING clause, or ORDER 
BY clause with a column function and no GROUP BY clause is specified.
Run Code Online (Sandbox Code Playgroud)

你能指出什么是错的吗?我对SQL没有多少经验.

谢谢.

Dav*_*ave 22

是的,你可以,但你应该对分组水平保持一致.也就是说,如果您的查询是GROUP BY查询,那么在分析函数中,您只能使用所选列的"非分析"部分中的"详细信息"列.因此,您可以使用GROUP BY列或非分析聚合,如下例所示:

select product_id, company, 
sum(members) as No_of_Members, 
sum(sum(members)) over(partition by company) as TotalMembership 
From Product_Membership 
Group by Product_ID, Company
Run Code Online (Sandbox Code Playgroud)

希望有所帮助

SELECT col_1, col_2, sum(Value) over(partition by col_1) as sum_value
    -- also try changing "col_1" to "col_2" in OVER
from myTable
GROUP BY col_2,col_1 
Run Code Online (Sandbox Code Playgroud)

  • 嗨,很好的例子。这是否意味着分区列需要是按列分组的子集?那么 `sum(sum(` ) 是什么意思? (2认同)

use*_*405 7

我找到了解决方案.

我不需要使用,OVER(PARTITION BY col_1)因为它已经在GROUP BY条款中.因此,以下查询给出了正确的答案:

SELECT col_1, col_2, sum(Value) as sum_value
from myTable GROUP BY col_1, col_2
Run Code Online (Sandbox Code Playgroud)

因为我已经分组了wrt col_1col_2.

戴夫,谢谢,我从你的帖子中得到了这个想法.