Sql query to return one single record per each combination in a table

前端 未结 2 790
被撕碎了的回忆
被撕碎了的回忆 2021-01-25 13:37

I need the result for every combination of (from_id, to_id) which has the minimun value and the loop matching a criteria.

So basically I need the loop that has the minim

2条回答
  •  盖世英雄少女心
    2021-01-25 14:02

    As I understand the problem this will work:

    SELECT  t.value, t.from_id, t.to_id, t.loop_id
    FROM    MyResults t
            INNER JOIN
            (   SELECT  From_ID, To_ID, MIN(Value) [Value]
                FROM    MyResults
                WHERE   Loop_ID % 2 = 0
                GROUP BY From_ID, To_ID
            ) MinT
                ON MinT.From_ID = t.From_ID
                AND MinT.To_ID = t.To_ID
                AND MinT.Value = t.Value
    

    However, if you had duplicate values for a From_ID and To_ID combination e.g.

    value     from_id   to_id     loop_id
    -------------------------------------
    
    0.1         A         B          2
    
    0.1         A         B          4
    

    This would return both rows.

    If you are using SQL-Server 2005 or later and you want the duplicate rows as stated above you could use:

    SELECT  Value, From_ID, To_ID, Loop_ID
    FROM    (   SELECT  *, MIN(Value) OVER(PARTITION BY From_ID, To_ID) [MinValue]
                FROM    MyResults
            ) t
    WHERE   Value = MinValue
    

    If you did not want the duplicate rows you could use this:

    SELECT  Value, From_ID, To_ID, Loop_ID
    FROM    (   SELECT  *, ROW_NUMBER() OVER(PARTITION BY From_ID, To_ID ORDER BY Value, Loop_ID) [RowNumber]
                FROM    MyResults
            ) t
    WHERE   RowNumber = 1
    

提交回复
热议问题