need a query to do a match

elsvieta 416 Reputation points
2025-07-09T15:21:43.62+00:00

Hi all,

I have these two tables:

T1

Date Item Qty
2025-07-01 100 10
2025-07-01 101 20
2025-07-02 100 30
2025-07-03 200 20
2025-07-04 200 30

and T2

Date Item Qty
2025-07-01 100 10
2025-07-02 105 30
2025-07-02 106 30
2025-07-03 205 20
2025-07-04 200 20

I need a query that gives me a result exactly like below:

Result Table
Date T1Qty T2Qty Diff(T1Qty-T2Qty)
2025-07-01 10 10 0
2025-07-01 20 20
2025-07-02 30 30 0
2025-07-02 0 30 -30
2025-07-03 20 20 0
2025-07-04 30 20 10

On aggregate, the Qty difference for 2025-07-01 is 20, whether I match my second row in T2 with the first row in T1 and I get a 10 difference for that row and then the first row in T1 is not matched with anything in T2 and there is another difference of 10.

However, I would like to match the quantities, as well, so that my result is like shown in the result table. The Item does not play any role.

Thanks,
elsvieta

SQL Server | SQL Server Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 123.6K Reputation points
    2025-07-09T16:08:17.9666667+00:00

    Try something like this:

    ;
    with Q1 as 
    (
    	select *, row_number() over (partition by [Date] order by Qty) as n
    	from T1
    ),
    Q2 as 
    (
    	select *, row_number() over (partition by [Date] order by Qty) as n
    	from T2
    )
    select coalesce(Q1.[Date], Q2.[Date]) as [Date], coalesce(Q1.Qty, 0) as T1Qty, coalesce(Q2.Qty, 0) as T2Qty, coalesce(Q1.Qty, 0) - coalesce(Q2.Qty, 0) as [Diff(T1Qty-T2Qty)]
    from Q1
    full outer join Q2 on Q1.[Date] = Q2.[Date] and Q1.n = Q2.n
    order by [Date], coalesce(Q1.Qty, Q2.Qty)
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.