简体   繁体   中英

One to Many relationship / for each in SQL query

I have two tables Table 1 & Table 2 and the relationship between of them is: one ---> many.

Table 1 --> CaseNumber is the PK | CreatedDate | ModifiedDate

Table 2 --> Id is the PK | CaseNumber is the FK | Age

Table 2 has many records for the same CaseNumber. I would like to query the following:

for each CaseNumber in Table 2 find the minimum Age . eg Find the minimum age of all records in Table 2.

Not for a specific CaseNumber . When I remove the where clause sth strange is happened. I cannot take the minimum for each case number. I am receiving more than row of the same casenumber. It seems that min(age) is not working.

I have some difficulties since the relationship is one to many. How can I handle that?

Sample records are the following:

Table 1 CaseNumber CreatedDate ModifiedDate

        1        12/12/2012 25/12/2012
        2        14/12/2012 15/12/2012
        3        16/12/2012 16/12/2012
        4        17/12/2012 17/12/2012
        5        17/12/2012 25/12/2012

Table 2 Id CaseNumber Age

      1  2         23
      2  2         34
      3  2         19
      4  3         25
      5  4         26
      6  4         50

I would like to return only 3 rows:

Case number 2 with Age 19

Case number 3 with age 25

Case number 4 with age 26

SELECT  CaseNumber, CreatedDate, ModifiedDate, 
        MIN(b.Age) Age
FROM    Table1 a
        INNER JOIN Table2 b
            ON a.CaseNumber = b.CaseNumber
WHERE   a.CaseNumber = 7
GROUP   BY CaseNumber, CreatedDate, ModifiedDate
SELECT  B.Id ,B.CaseNumber,MIN(B.Age),A.CreateDate ,
        A.ModifiedDate
FROM    TABLE1 A
        INNER JOIN TABLE2 B ON A.CaseNumber = B.CaseNumber
WHERE   B.CaseNumber = 7
GROUP BY B.Id,B.CaseNumber,A.CreateDate,A.ModifiedDate
SELECT  B.Id ,B.CaseNumber,MIN(B.Age),A.CreateDate ,
        A.ModifiedDate
FROM    TABLE1 A
        INNER JOIN TABLE2 B ON A.CaseNumber = B.CaseNumber
WHERE   B.CaseNumber IN (SELECT CaseNumber from Table2)
GROUP BY B.Id,B.CaseNumber,A.CreateDate,A.ModifiedDate

You try this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM