Search code examples
sqlgroup-by

SQL group by records only when sum(percentage) < 100 if not display the record as is


Trying to perform group by operation where records should be grouped only when percentage is less then 100, if 100 or more it should be kept as is.

Sample Data:

enter image description here

Expected Output:

enter image description here

Group by query I am trying is:

SELECT ID,SUM(Percentage),SUM(Value)
From table
GROUP BY ID

Solution

  • Select data with <100 and >=100 independently, and the use UNION BY:

    SELECT ID, SUM(Percentage), SUM(Value)
      From table
     where Percentage < 100
     GROUP BY ID
    
    UNION ALL
    
    SELECT ID, Percentage, Value
      From table
    where Percentage>=100