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

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

    Using CTE (SQL Server 2005+):

    WITH max_feature AS (
       SELECT c.id,
              c.parent,
              MAX(c.feature) 'feature'
         FROM CHILD c
     GROUP BY c.id, c.parent)
       SELECT p.id,
              p.text,
              mf.id,
              mf.parent,
              mf.feature
         FROM PARENT p
    LEFT JOIN max_feature mf ON mf.parent = p.id
    

    Non CTE equivalent:

       SELECT p.id,
              p.text,
              mf.id,
              mf.parent,
              mf.feature
         FROM PARENT p
    LEFT JOIN (SELECT c.id,
                      c.parent,
                      MAX(c.feature) 'feature'
                 FROM CHILD c
             GROUP BY c.id, c.parent) mf ON mf.parent = p.id
    

    Your question lacks details for handling tie breakers (when 2+ CHILD.id values have the same feature value). Agent_9191's answer uses TOP 1, but that will take the first that is returned & not necessarily the one you want.

提交回复
热议问题