我有一个包含3列的表myTable
。 col_1
是INTEGER
,其他2列是DOUBLE
。例如,col_1={1, 2}, col_2={0.1, 0.2, 0.3}
。 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
我想要的是在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
我尝试了以下SQL查询:
SELECT col_1, col_2, sum(Value) over(partition by col_1) as sum_value
from myTable
GROUP BY col_1, col_2
但是在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.
你能指出错误吗?我对SQL没有多少经验。
谢谢。
答案 0 :(得分:20)
是的,你可以,但你应该对分组水平保持一致。 也就是说,如果您的查询是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
希望有所帮助
SELECT col_1, col_2, sum(Value) over(partition by col_1(also try changing this to "col_2"))) as sum_value
from myTable
GROUP BY col_2,col_1
答案 1 :(得分: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
因为我已经分组w {。col_1
和col_2
。