Cannot use group by and over(partition by) in the same query?

后端 未结 2 675
逝去的感伤
逝去的感伤 2020-12-30 04:01

I have a table myTable with 3 columns. col_1 is an INTEGER and the other 2 columns are DOUBLE. For example, col_1={

相关标签:
2条回答
  • 2020-12-30 04:27

    Yes, you can, but you should be consistent regarding the grouping levels. That is, if your query is a GROUP BY query, then in an analytic function you can only use "detail" columns from the "non-analytic" part of your selected columns. Thus, you can use either the GROUP BY columns or the non-analytic aggregates, like this example:

    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
    

    Hope that helps

    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 
    
    0 讨论(0)
  • 2020-12-30 04:30

    I found the solution.

    I do not need to use OVER(PARTITION BY col_1) because it is already in the GROUP BY clause. Thus, the following query gives me the right answer:

    SELECT col_1, col_2, sum(Value) as sum_value
    from myTable GROUP BY col_1, col_2
    

    since I am already grouping w.r.t col_1 and col_2.

    Dave, thanks, I got the idea from your post.

    0 讨论(0)
提交回复
热议问题