SQL: Select maximum value for each unique key?

前端 未结 3 892
盖世英雄少女心
盖世英雄少女心 2020-12-21 18:17

Sorry, I\'m not sure how to phrase that and I\'m really not very good with SQL. The db engine i SQL Server Compact. I currently have this query:

SELECT *
FRO         


        
3条回答
  •  隐瞒了意图╮
    2020-12-21 19:08

    Will work with SQL Server 2005+:

    WITH maxHits AS(
      SELECT s.threadid,
             MAX(s.hitcount) 'maxhits'
        FROM SAMPLES s
        JOIN CALLERS c ON c.threadid = s.threadid AND c.calleeid != s.functionid
    GROUP BY s.threadid
    )
    SELECT t.*
      FROM SAMPLES t
      JOIN CALLERS c ON c.threadid = t.threadid AND c.calleeid != t.functionid
      JOIN maxHits mh ON mh.threadid = t.threadid AND mh.maxhits = t.hitcount
    

    Work on any database:

    SELECT t.*
      FROM SAMPLES t
      JOIN CALLERS c ON c.threadid = t.threadid AND c.calleeid != t.functionid
      JOIN (SELECT s.threadid,
                   MAX(s.hitcount) 'maxhits'
              FROM SAMPLES s
              JOIN CALLERS c ON c.threadid = s.threadid AND c.calleeid != s.functionid
          GROUP BY s.threadid) mh ON mh.threadid = t.threadid AND mh.maxhits = t.hitcount
    

提交回复
热议问题