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

后端 未结 5 1811
别那么骄傲
别那么骄傲 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:11

    If you need to join different from a MAX column and any columns described in a group by closure of a nested select, you can use an APPLY function. It is a simplest solution. You also can use WITH operator. But that look harder.

    SELECT p.id, p.text, CHILD_ROW.ANY_COLLUMN
    FROM parent p
    OUTER APPLY (SELECT TOP 1 child.ANY_COLLUMN
                      FROM child
                      WHERE child.parent = p.id
                      ORDER BY child.feature DESC 
                      ) CHILD_ROW
    

提交回复
热议问题