Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

tsql problem - matching up date ranges

$
0
0
The problem that I have can be demonstrated by the 2 datasets below. The first dataset is our source data, the second data set is the desired result. 

We have 3 account numbers in our source data 1-3, each account can have 2 types of transaction associated with (A or B), each transaction has a date range associated with it (start and end date) and each transaction has a value.

What we need to do is where we can for each account match up transactions for each type where the date ranges coincide. (01-Jan to 31-Jan for type A matches up with 01-Jan to 31-Jan for type B) However it is not that simple if there are 2 contiguous date ranges then these can be aggregated up for an account/type combination if it results in period matching, if it doesn't result in period matching then they shouldn't be aggregated. In the example below for accounted 1 there are two type A transactions i. 01-16 Jan and ii. 17-31 Jan and a single type B transaction 1-31 Jan, because the 2 Jan type A
transactions are contiguous and can be aggregated up to match exactly with a corresponding type B transaction then code I am trying to write will aggregate the two type A rows then match them to the type B row. The  datasets below will better demonstrate this.

SELECT 1 acc_id,'A' type,'2012-jan-01'  start,'2012-jan-16' [END],1 val UNION
SELECT 1,'A','2012-jan-17','2012-jan-31',2 UNION
SELECT 1,'B','2012-jan-01','2012-jan-31',3 UNION
SELECT 2,'A','2012-jan-01','2012-jan-14',4 UNION
SELECT 2,'A','2012-jan-15','2012-jan-31',5 UNION
SELECT 2,'B','2012-jan-01','2012-jan-31',6 UNION
SELECT 3,'A','2012-jan-01','2012-jan-14',7 UNION
SELECT 3,'B','2012-jan-01','2012-jan-31',8


SELECT 1 acc_id,'2012-jan-01' start,'2012-jan-31' [end],'A' type,3 val,'B' type,3 val UNION -- The A value is made up of the sum of the 2 A rows for this account because the 2 A rows match correspond exactly to the B row
SELECT 2,'2012-jan-01','2012-jan-31','A',9,'B',6 UNION -- The A value is made up of the sum of the 2 A rows for this account because the 2 A rows match correspond exactly to the B row
SELECT 3,'2012-jan-01','2012-jan-14','A',7,NULL,NULL UNION --there is no B period that matches this A period for this account hence NULLS
SELECT 3,'2012-jan-01','2012-jan-31',NULL,NULL,'B',8 -- there is no A period that matches this B period for this account hence NULL




Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>