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

后端 未结 9 841
别跟我提以往
别跟我提以往 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 10:13

    In general, try using Subqueries rather than joining and grouping - it often makes SQL that is much easier to understand.

    SELECT Nick,
       (SELECT Description from Reasons WHERE Reasons.ID = (
           SELECT FIRST(Marks.ReasonId) from Marks WHERE Marks.PlayerID = Players.ID)
       ),
       (SELECT SUM(Value) from Marks WHERE Marks.PlayerID = Players.ID)
    
    0 讨论(0)
  • 2020-12-29 10:16

    Is this an opportunity to use a 'HAVING' clause ? (You want to discriminate on an aggregate function - 'Sum') ?

    0 讨论(0)
  • 2020-12-29 10:18

    SQL Server 2005 you can use this:

    declare @sometable table ( foo int, bar int, value int )

    insert into @sometable values (1, 5, 10) insert into @sometable values (1, 4, 20) insert into @sometable values (2, 1, 1) insert into @sometable values (2, 1, 10) insert into @sometable values (2, 1, 1) insert into @sometable values (2, 2, 13) insert into @sometable values (3, 4, 25) insert into @sometable values (3, 5, 1) insert into @sometable values (3, 1, 1) insert into @sometable values (3, 1, 1) insert into @sometable values (3, 1, 1) insert into @sometable values (3, 1, 1) insert into @sometable values (3, 1, 1)

    -- temp table for initial aggregation declare @t2 table (foo int, bar int, sums int) insert into @t2 select foo, bar, sum(value) from @sometable group by foo, bar

    select * from ( SELECT foo, bar, sums, ROW_NUMBER() OVER (PARTITION BY Foo ORDER BY Sums DESC) ROWNO FROM @t2) x where x.ROWNO = 1

    0 讨论(0)
提交回复
热议问题