Forum Discussion
yevhen_87
1 year agoFrequent Visitor
Joins within a query
Is it possible to left join table on the left with itself to make it look like a table on the right?
- Anonymous1 year ago
Hi yevhen_87 ,
Please try this M code:
let // My data source Source = Table.FromRecords({ [period = #date(2024, 1, 9), id = 1, values = 12], [period = #date(2024, 1, 9), id = 2, values = 26], [period = #date(2024, 1, 9), id = 3, values = 25], [period = #date(2024, 1, 9), id = 4, values = 12], [period = #date(2024, 1, 10), id = 1, values = 32], [period = #date(2024, 1, 10), id = 2, values = 25], [period = #date(2024, 1, 10), id = 3, values = 16] }), // Convert the period column to date type ChangeType = Table.TransformColumnTypes(Source, {{"period", type date}}), // Find the latest and second latest dates DistinctDates = Table.Distinct(Table.SelectColumns(ChangeType, {"period"})), SortedDates = Table.Sort(DistinctDates, {{"period", Order.Descending}}), LatestDate = SortedDates{0}[period], SecondLatestDate = SortedDates{1}[period], // Create the table for the latest date LatestTable = Table.SelectRows(ChangeType, each [period] = LatestDate), // Create the table for the second latest date SecondLatestTable = Table.SelectRows(ChangeType, each [period] = SecondLatestDate), // Rename columns in both tables to avoid name conflicts RenameLatestTable=Table.RenameColumns(LatestTable,{{"values","Current"}}), RenameSecondLatestTable=Table.RenameColumns(SecondLatestTable,{{"period","periodTemp"},{"id","idTemp"},{"values","previous"}}), // Merge tables MergedTable=Table.Join(RenameLatestTable,{"id"},RenameSecondLatestTable,{"idTemp"},JoinKind.LeftOuter), Result=Table.RemoveColumns(MergedTable,{"periodTemp","idTemp"}) in ResultBest Regards,
Bof
Anonymous
1 year agoNot applicable
Just load the table, select merge, and for the second table, just select the first table again, select full outer join. Done.
--Nate
yevhen_87
1 year agoFrequent Visitor
I get this
from this
- Anonymous1 year agoNot applicable
OK I understand what you mean now. Make sure your table is sorted on ID AND THEN DATE, add an index column, starting with one, and then an index column, starting with zero, and then use the merge GUI to join the table to itself by selecting the current table as your right table, join on the zero index in the first column, and the one index in the second column.
--Nate