Search code examples
sqlsql-serversql-server-2012

SQL Query Last value of child table


I have two tables where primary key is uniqueidentifier and there are not dates inside of them. One table has info where is stored and has relationship to another table which is tracking status, each status is new row for history purpose. Now the problem is taking last row from second table and status.

Table 1

Column Type
Id uniqueidentifier
BoxNum nvarchar(25)

Table 2

Column Type
Id uniqueidentifier
status int
Table1_FK_ID uniqueidentifier

Status has the following meaning:

0 for new
10 - approved
20 - rejected
30 - blocked

Each box can be rejected than approved or opposite. So my question is how I can get last inserted record in table2, something like this:

Result

BoxNum Status
444444 10
444445 20
444412 30

Solution

  • If uniqueidentifier is sequential you can also use subquery like that;

    SELECT 
       T1.BoxNum,
       (SELECT TOP 1 T2.Status 
          FROM [Table 2] T2 
             WHERE T2.Table1_FK_ID = T1.Id ORDER BY T2.Id DESC) AS Status
    FROM [Table 1] T1
    

    But if there is no related data in second table it could be error, then you need to check data existence.