Question

I am trying to run this query in postgresql but getting this error: "ERROR: Aggregate function calls may not be nested". I am not sure what the problem or a solution for this.

Here is my query:

select a.KEY_NBR, a.MAIN_ID
        , 
            case
                when a.KEY_NBR = a.MAIN_ID
                    then 'Don''t Use'
                when a.count = MAX(a.count) over(partition by a.KEY_NBR)
                    then 'Good'
                else 'Bad'
            end [flag]
    from MYTABLE a
Was it helpful?

Solution

Your query looks ok and should work. Perhaps the version you use has some limitations. Try this variation:

WITH a AS
  ( SELECT key_nbr, main_id, count,
           MAX(count) OVER (PARTITION BY key_nbr) AS max_count
    FROM mytable
  ) 
SELECT a.key_nbr, a.main_id,
       CASE WHEN a.key_nbr = a.main_id
                THEN 'Don''t Use'
            WHEN a.count = max_count 
                THEN 'Good'
            ELSE 'Bad'
       END AS flag
FROM a ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top