SQL Server Join two tables with not exactly matching dates in sql

zsohkypk  于 2023-10-15  发布在  其他
关注(0)|答案(5)|浏览(136)

I have a table with dates that are about 1 month before the other table.

For example, one table reports 1st quarter end on March 31st and the other reports 1st quarter end on February 28th (or 29th) but it would be perfectly fine to join them together by the date regardless that the two dates arent exactly the same.

Any suggestions, please.

Thanks

t1qtbnec

t1qtbnec1#

You can join on DateDiff(dd, Date1, Date2) < x

Or to get more exact

select endOfMonth.*, begOfMonth.* 
from endOfMonth join begOfMonth 
on DATEADD (dd , 1 , endOfMonth.date ) = begOfMonth.Date
kognpnkq

kognpnkq2#

Your ON clause could look at year and quarter for a match:

ON TABLE1.YEAR([1st quarter end ]) = TABLE2.YEAR([1st quarter end ])
AND TABLE1.QUARTER([1st quarter end ]) = TABLE2.QUARTER([1st quarter end ])
a1o7rhls

a1o7rhls3#

One approach would be to use the DATEPART() function that returns the quarter for any given date. Then you would be able to join on the returned quarter.

Sample SQL:

SELECT *
FROM 
(
    SELECT DATEPART(QUARTER,date_column) AS t1_quarter
    FROM table1
    UNION ALL
    SELECT DATEPART(QUARTER,date_column) AS t2_quarter
    FROM table2
) AS temp
WHERE temp.t1_quarter = temp.t2_quarter;

Put any other fields as you require (ID fields most probably) in the internal SELECTS.

vjhs03f7

vjhs03f74#

If I rigthly understood you and you have the same number of column in those tables then you should use UNION in your SQL-query. See more information about UNION here: http://en.wikipedia.org/wiki/Set_operations_%28SQL%29 .

von4xj4u

von4xj4u5#

select 
  val1 
From 
  Table1 T1 
  inner Join Table2 t2 
  on MONTH(T1.date1) = MONTH(t2.date1) 
  And YEAR(T1.date1) = YEAR(t2.date1)

相关问题