Skip to content
Advertisement

How to use case statement and min() with group by?

The following query when I that execute

SELECT CASE
         WHEN spd.IS_MAIN_DEFECT='Y' 
           THEN spd.piece_Defect_num_id 
         ELSE min(spd.PIECE_DEFECT_NUM_ID)
       END AS defect
  FROM piece P,
       STY_PIECE_DEFECT spd,
       STY_DEFECT_CATALOGUE sdc,
       piece_history ph,
       piece_history_out pho,
       PLANT_CONFIG pc
  (...inner join and where clause)
  GROUP BY p.PIECE_ID,
           CASE
             WHEN spd.IS_MAIN_DEFECT='Y'
               THEN spd.piece_Defect_num_id
             ELSE min(spd.PIECE_DEFECT_NUM_ID)
           end 

It seems error

ORA-00934: group function is not allowed here

I guess , there is error min() in group by.

How can I solve this problem?

Advertisement

Answer

You have to use analytical MIN() function like the below without group by

     SELECT distinct CASE WHEN spd.IS_MAIN_DEFECT='Y' 
      THEN spd.piece_Defect_num_id 
       ELSE min(spd.PIECE_DEFECT_NUM_ID) over () END AS defect
      FROM piece P , STY_PIECE_DEFECT spd ,STY_DEFECT_CATALOGUE sdc ,piece_history ph 
      , piece_history_out pho, PLANT_CONFIG pc
      (...inner join and where clause)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement