0

I have two tables and I only want a start date from a query on table2 to be added to the values on table1. The start date is deduced with a GROUP BY statement, for example:

Table 1

ID Summary End
1 Heading 01/01/2023
2 Heading 2 02/02/2023

Table 2

ID Summary Start Parent ID
3 Heading 01/10/2022 1
4 Heading 2 02/10/2023 1
5 Heading 3 03/10/2023 2

I would like to have all of table 1 with just the minimum start date for each Parent ID from Table 2.

I tried something like this but I can't get the extra columns to return, I'm guessing I need to change something with the GROUP BY clause?

SELECT table1.*, t2.Start
FROM table1 INNER JOIN 
(
    SELECT [Parent ID], min(Start)
    FROM table2
    GROUP BY [Parent ID]
) t2 ON t2.[Parent ID] = t1.ID
Skully
  • 2,882
  • 3
  • 20
  • 31

4 Answers4

1
SELECT t1.*, t2.Start
FROM table1 t1 inner join 
    (
        select [Parent ID], min(Start) as Start
        from table2
        group by [Parent ID]
    ) t2 on t2.[Parent ID] = t1.ID
Rams
  • 2,129
  • 1
  • 12
  • 19
1

An other way to do it is by using GROUP BY and the aggregation function min() :

select t1.ID, max(t1.Summary) as Summary, max(t1.End) as End, min(t2.Start_) as min_start
from table1 t1
inner join table2 t2 on t1.id = t2.Parent_ID
group by t1.ID
SelVazi
  • 10,028
  • 2
  • 13
  • 29
0
;with a as(
Select row_number() over (PARTITION BY Table1.id order by table2.start) as 'row',table1.*,table2.start)
from table1 left join table2 on table1.id=table2.id)
select * from a where row=1
GMB
  • 216,147
  • 25
  • 84
  • 135
0

An alternative solution rather than using a GROUP BY clause is to fetch the result within a subquery instead.

SELECT t1.*, (
    SELECT min(Start)
    FROM table2 t2
    WHERE t2.ParentID = t1.ID
) 
FROM table1 t1;
Skully
  • 2,882
  • 3
  • 20
  • 31
toha
  • 5,095
  • 4
  • 40
  • 52
  • 1
    Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you edit your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Skully May 12 '23 at 15:36
  • 1
    This is a solution sharing platform where giving your answer is one part, but explaining it to allow future readers to understand what the solution is doing is equally as important. Whilst it is not a rule, it is highly encouraged to do so. – Skully May 13 '23 at 18:01