Home > Software design >  SQL Group By Query With Specific First Row
SQL Group By Query With Specific First Row

Time:11-24

I'm using this query to pull information about companies and their scores from a ms sql database.

  SELECT company, avg(score) AS Value FROM Responses where id=12 group by company 

This is the result

 |   COMPANY     | VALUE |

 |: ------------ | ------:|

 | Competitor A  | 6.09   |

 | Competitor B  | 5.70   |

 | Other Brand   | 5.29   |

 | Your Brand    | 6.29   |

What I need is a query that will put one company that I will specify in the first position (in this case, the company is Your Brand) and then order the rest by the company like this.

 |   COMPANY     | VALUE |

 |: ------------ | -----:|

 | Your Brand    | 6.29   |

 | Competitor A  | 6.09   |

 | Competitor B  | 5.70   |

 | Other Brand   | 5.29   |

 

CodePudding user response:

As @jarlh has suggested, use a CASE expression to order:

SELECT company, AVG(score) AS Value
FROM Responses
WHERE id = 12
GROUP BY company
ORDER BY CASE company WHEN 'Your Brand' THEN 0 ELSE 1 END,
         AVG(score) DESC;
  •  Tags:  
  • sql
  • Related