• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 508
  • Last Modified:

Select Top row from child table

I am writing a sproc to return rows from tableA and I need the first row that was entered in child tableB.

 TableA
A_ID              PK Identity
JobNumber  

TableB
B_ID                 PK Identity
A_ID                 FK  int
DateEntered
Comment

I am close but not there yet. Since the PK in tableB is an identity I think I'm safe selecting the row that has the min(B_ID) WHERE tableB.A_ID = tableA.A_ID

So I have this
SELECT * FROM tableA, (SELECT DateEntered,Comment FROM tableB  WHERE tableB.A_ID = tableA.A_ID)

Hung up getting the rest. Still trying but would like some help.
0
AkAlan
Asked:
AkAlan
  • 3
1 Solution
 
tigin44Commented:
SELECT A.*, B. DateEntered, B.Comment
FROM tableA A
   INNER JOIN (SELECT A_ID, MIN(DateEntered) AS DateEntered, MIN(Comment) AS Comment FROM tableB GROUP BY A_ID) B ON A.A_ID = B.A_ID
0
 
Ephraim WangoyaCommented:


SELECT * FROM tableA, (SELECT top 1 DateEntered,Comment FROM tableB WHERE tableB.A_ID = tableA.A_ID order by dateentered)
0
 
Ephraim WangoyaCommented:
Posted the wrong one

SELECT *, (SELECT top 1 DateEntered,Comment FROM tableB WHERE tableB.A_ID = tableA.A_ID order by dateentered)
 FROM tableA
0
 
Ephraim WangoyaCommented:

Disregard my post
0
 
SharathData EngineerCommented:
try this query.
SELECT * 
  FROM (SELECT t1.A_ID,t1.JobNumber,t2.B_ID,t2.DateEntered,t2.Comment, 
               ROW_NUMBER() 
                 OVER(PARTITION BY t1.A_ID ORDER BY t2.B_ID) rn 
          FROM TableA t1 
               JOIN TableB t2 
                 ON t1.A_ID = t2.A_ID) t1 
 WHERE rn = 1

Open in new window

0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now