one-to-many query selecting all parents and single top child for each parent

后端 未结 5 1795
别那么骄傲
别那么骄傲 2020-12-24 07:31

There are two SQL tables:

Parents:
+--+---------+
|id|   text  |
+--+---------+
| 1|  Blah   |
| 2|  Blah2  |
| 3|  Blah3  |
+--+---------+

Childs
+--+-----         


        
5条回答
  •  执念已碎
    2020-12-24 08:15

    manji's query does not handle tie-breakers for max feature. Here is my method, which I've tested:

    ;WITH WithClause AS (SELECT p.id, p.text, 
            (SELECT TOP 1 c.id from childs c 
                where c.parent = p.id order by c.feature desc) 
            AS BestChildID
        FROM Parents p) 
    SELECT WithClause.id, WithClause.text, c.id, c.parent, c.feature
    FROM WithClause 
    LEFT JOIN childs c on WithClause.BestChildID = c.id
    

提交回复
热议问题