Selecting SQL from a group

Suppose we have the following table data:

ID   parent    stage     submitted
1      1         1           1
2      1         2           1
3      1         3           0
4      1         4           0
5      5         1           1
6      5         2           1
7      5         3           1
8      5         4           1

      

As you can see, we have two groups (having the same parent). I want to select the last stage to be sent. In the example above, I want to select IDs 2 and 8. I am completely lost, so if anyone can help it would be greatly appreciated. :)

+1


a source to share


4 answers


SELECT T.ID, T.PARENT, T.STAGE 
from
   T, 
   (
      select PARENT, MAX( STAGE) MAX_STAGE 
      from T
      where SUBMITTED = 1
      GROUP BY PARENT 
   ) M
where 
   T.STAGE = M.MAX_STAGE 
   AND T.PARENT = M.PARENT

      



Explanation: First, isolate the maximum stage for each group with represented = 1 (internal selection). Then join the result with a real table to filter out records without a maximum step.

+8


a source


Select Parent, max(Id)
From tbl t
Inner Join
(
    Select Parent, max(Stage) as Stage
    from tbl t
    Where Submitted = 1
    Group by Parent
) submitted
on t.Parent = submitted.parent and
    t.stage = submitted.stage
Group by Parent

      



+1


a source


This should do it:

SELECT
     T1.id,
     T1.parent,
     T1.stage,
     T1.submitted
FROM
     Some_Table T1
LEFT OUTER JOIN Some_Table T2 ON
     T2.parent = T1.parent AND
     T2.submitted = 1 AND
     T2.stage > T1.stage
WHERE
     T1.submitted = 1 AND
     T2.id IS NULL

      

+1


a source


SELECT * FROM Table WHERE ID = 2 OR ID = 8

      

Is this what you want?

-1


a source







All Articles