How do I select the first row per group in an SQL Query?

后端 未结 9 995
别跟我提以往
别跟我提以往 2020-12-29 09:26

I\'ve got this SQL query:

SELECT   Foo, Bar, SUM(Values) AS Sum
FROM     SomeTable
GROUP BY Foo, Bar
ORDER BY Foo DESC, Sum DESC

This resul

9条回答
  •  心在旅途
    2020-12-29 09:55

    I might disagree with rjmunru in that using Ansii style joins can often be easier to read than subqueries but to each his own -- I just follow what our DBAs say to do.

    If you just want the first result from a query, you might be able to use a rownum (if using oracle, other databases probably have something similiar).

    select * from foo_t f where f.bar = 'bleh' and rownum = 1

    Of course a HAVING clause might also be appropriate, depending on what you are trying to do.

    "HAVING is used to perform an action on groups created by GROUP BY similar to that of the WHERE clause on rows in a basic SQL statement. The WHERE clause limits the rows evaluated. The HAVING clause limits the grouped rows returned."

    hth

提交回复
热议问题