I have this sample data below (table1):
PKEY DATE
---- ----
ABC1 2/13
CFG5 1/05
POK9 1/10
and I have these dates from another table (table2):
PKEY REF# DATE
---- ---- ----
1 ABC1 2/14
2 ABC1 2/20
3 ABC1 3/01
4 CFG5 3/05
5 CFG5 2/10
6 ABC1 2/25
I want to get the max date from table2 (per REF#) and get the difference with the date from table1. showing the below result.
REF# DIFF
---- ----
POK9 55
CFG5 54
ABC1 21 [ *note: this is equal to datediff(day,table1.DATE,getdate()) ]
*ALSO, i want to use the date today (to be deducted with the date from table1) if REF# is not existing in table2 (like the 3rd row in the above example). Hope this makes sense.. let me know if there's anything unclear so I can edit right away..
**UPDATE: this is what i've tried so far.. but still incomplete.. thanks for the hardwork
select t1.[REF#]
from table1 as t1
join table2 as t2
on t1.[REF#] COLLATE DATABASE_DEFAULT = t2.[REF#] COLLATE DATABASE_DEFAULT
Something like this?
Edited for comments: You should be able to filter like this:
or by wrapping the statment like this:
Demo on SQLFiddle
OR without APPLY() operator
query with your criteria