Forum Discussion

eWise's avatar
eWise
Icon for Helper II rankHelper II
3 years ago
Solved

Get nearest date to target date from another table

I have two tables, one for scan items with ScanDate and another table for warehouses with warehouse AccessTime. Am trying to get the nearest AccessTime to the ScanDate for each item. It could be befo...
  • v-yueyunzh-msft's avatar
    3 years ago

    Hi, eWise 

    According to your description , there is no associated [AcessTime] field in the scan table and you want to show the [UserId] field in the 'Scans' table. I download your .csv files , the [warehouseId] in the fourth row of your 'Scans' table does not have the data to be associated with in the 'WarehouseAccess' table, so the display is empty.

     

    Here are the steps you can follow:

    (1)I use the data you provided, the two table do not need to create relationship.

    (2)We can click "New column"  create two calculated columns in 'Scans' table : 

    AccessTime = var _groupBy_ID =DISTINCT( SELECTCOLUMNS( FILTER('WarehouseAccess' , 'WarehouseAccess'[warehouseId]='Scans'[warehouseId]) ,"AccessTime", [AccessTime] ))
    var _compare_table =ADDCOLUMNS( CROSSJOIN({'Scans'[ScanDate]},_groupBy_ID) , "diff" ,ABS( [AccessTime]-[ScanDate]) )
    var _min_diff= MINX(_compare_table ,[diff])
    var _min_date = FILTER(_compare_table , [diff] =_min_diff) 
    return
    CONCATENATEX(_min_date,[AccessTime],",")
    UserId = var _groupBy_ID =DISTINCT( SELECTCOLUMNS( FILTER('WarehouseAccess' , 'WarehouseAccess'[warehouseId]='Scans'[warehouseId]) ,"AccessTime", [AccessTime] ))
    var _compare_table =ADDCOLUMNS( CROSSJOIN({'Scans'[ScanDate]},_groupBy_ID) , "diff" ,ABS( [AccessTime]-[ScanDate]) )
    var _min_diff= MINX(_compare_table ,[diff])
    var _min_date =SELECTCOLUMNS( FILTER(_compare_table , [diff] =_min_diff) , "date", [AccessTime])
    var _user_table = FILTER('WarehouseAccess' , 'WarehouseAccess'[warehouseId]='Scans'[warehouseId] && 'WarehouseAccess'[AccessTime] in _min_date )
    return
    CONCATENATEX(_user_table,[userId],",")

    (3)Then we can meet your need , the result is as follows:

    If this method cannot meet your need ,you can provide special output data as a table so that we can help you better .

     

    Best Regards,

    Aniya Zhang

    If this post helps, then please consider Accept it as the solution to help the other members find it more quickly

  • eWise's avatar
    eWise
    3 years ago

    Much thanks v-yueyunzh-msft this worked as intended.