sql server - Closest Date in SQL -


i trying find nearest date or actual date between table_a , table_b in sql server 2012

table_a

date ------- 2017-07-15 00:00:00 2017-07-27 00:00:00 2017-07-23 00:00:00 

table_b

dt ------ 2017-07-17 00:00:00 2017-07-19 00:00:00 2017-07-23 00:00:00 2017-07-28 00:00:00 

conditions:

  • if table_a.date = table_b.dt table_a.date
  • if table_a.date <> table_b.dt whichever next higher date in table_b

desired output:

date ----- 2017-07-17 00:00:00 2017-07-23 00:00:00 2017-07-28 00:00:00 

any or guidance?

use cross apply , top:

select      date = x.dt table_a cross apply(     select top(1) dt     table_b b     b.dt >= a.date     order b.dt ) x order x.dt 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -