Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a SQL table similar to this (MSSQL 2017 Standard)

Key Period  Year    Srce   Destination   Amt
001 001    2018     A      B             100
002 001    2018     A      C             200
003 001    2018     B      A             99
004 001    2018     C      A             180


Initial transfers in first two rows, reciprocal in 2nd two rows

I need to get this (1 row for each in reciprocal transfer
Prd Year Srce SourceAmount  Dest Variance Source Dest Period Year Amount
001 2018 A    100           B    1        B      A    001    2018 99
001 2018 A    100           C    20       C      A    001    2018 180


Basically, a pivoted single row showing matching source/dest dest/source with variance

Please help, thanks in advance.

What I have tried:

Recursive CTE, PIVOTs etc. , nothing seems to be getting me the results i expect

This will eventually feed an SSRS report.
Posted
Updated 7-Jun-18 0:14am
v2
Comments
CHill60 7-Jun-18 4:00am    
Why not post the code that came closest to the results you want and we can go from there.
You could also try explaining what a reciprocal transfer is too, you have given us no context whatsoever.
And the fact it will eventually feed into an SSRS report isn't really relevent to the problem

Please try
SQL
SELECT     period, year,
	CASE WHEN srce<destination THEN srce ELSE destination END as srce,
	CASE WHEN srce<destination THEN destination ELSE srce END as dest,
	SUM(CASE WHEN srce<destination THEN amt ELSE -amt END) as variance,
	SUM(CASE WHEN srce<destination THEN amt ELSE 0 END) as srcamount,
	SUM(CASE WHEN srce<destination THEN 0 ELSE amt END) as destamount
FROM         dbo.data
GROUP BY period,year, 
	CASE WHEN srce<destination THEN srce ELSE destination END,
	CASE WHEN srce<destination THEN destination ELSE srce END
 
Share this answer
 
Seems you need to combine data based on period, year and source/destination

SQL
SELECT t1.Period AS Prd, t1.Year AS Year1, t1.Srce AS Src1, t1.Amt AS SourceAmount, t1.Desttination AS Dest1,
    t2.Amt - t1.Amt AS Variance, t2.Srce As Src2, t2.Destination AS Dest2, t2.Period, t2.Year AS Year2, t2.Amd AS Amount
FROM YourTable AS t1
    INNER JOIN YourTable As t2 ON 
        t1.Period = t2.Period AND 
        t1.Year = t2.Year AND
        t1.Srce = t2.Destination AND
        t1.Key < t2.Key


More about joins: Visual Representation of SQL Joins[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900