I have a mysql table that looks like this:
table1
User_ID | Serial | Warranty
1 | 12 | 2024-01-01
4 | 13423 | 2022-11-21
1 | 643r | 2026-05-13
4 | r42r4 | 2023-10-07
5 | 743f | 2026-06-22
6 | 4324 | 2027-04-15
table2
ID | Name | Side | Serial
1 | Bob | Left | 12
4 | Mark | Right | 13423
1 | Bob | Right | 643r
4 | Mark | Left | r42r4
5 | Ella | Left | 743f
6 | Deb | Right | 4324
I need a query that will combine all the details into one result like this, for instance:
User_ID | Name | Left Warranty | Right Warranty | Left Serial | Right Serial
5 | Ella | 2026-06-22 | null | 743f | null
4 | Mark | 2023-10-07 | 2022-11-21 | r42r4 | 13423
1 | Bob | 2024-01-01 | 2026-05-13 | 12 | 643r
6 | Deb | null | 2027-04-15 | null | 4324
I know how to group, but I’m stuck completely on the logic to combine these table into a central query result with all the combined record information based on the serial numbers.
3
Answers
Not clear what table1 is bringing to the party, as dougp said.
But simple conditional aggregation would work for the sample data in table2. The general term for this is "pivoting".
A join will do the trick.
You need an
OUTER JOIN
and define the join on two columns (User_ID and Serial), use aCASE
statement to manually pivot the data, then aggregate somehow (I useMAX()
below) to consolidate the results to eliminate duplicate rows that contain NULLs.