ByQuarter
Distribute values across quarters
DROP TABLE Insurance;DROP TABLE quarters;
CREATE TABLE Insurance (
policynumber VARCHAR(10) NOT NULL PRIMARY KEY,
premium INT,
TransEff datetime,
TransExp datetime
);
INSERT INTO Insurance VALUES ('PACA1',490,'2012-04-27','2013-04-27');
INSERT INTO Insurance VALUES ('PACA2',100,'2012-04-27','2012-08-05');
CREATE TABLE quarters(
lo DATETIME NOT NULL PRIMARY KEY,
hi DATETIME NOT NULL
);
INSERT INTO quarters VALUES ('2012-01-01','2012-04-01');
INSERT INTO quarters VALUES ('2012-04-01','2012-07-01');
INSERT INTO quarters VALUES ('2012-07-01','2012-10-01');
INSERT INTO quarters VALUES ('2012-10-01','2013-01-01');
INSERT INTO quarters VALUES ('2013-01-01','2013-04-01');
INSERT INTO quarters VALUES ('2013-04-01','2013-07-01');
INSERT INTO quarters VALUES ('2013-07-01','2013-10-01');
INSERT INTO quarters VALUES ('2013-10-01','2014-01-01');
In this example you want to distribute the income across several quarters
SELECT policynumber,datepart(YEAR,l1) y,datepart(quarter,l1) q,l1,h1,
CASE WHEN l1>l2 THEN l1 ELSE l2 END AS maxstart,
CASE WHEN h1>h2 THEN h2 ELSE h1 END AS minend
FROM
(SELECT policynumber,TransEff,
CAST(lo AS INT) l1,CAST(transeff AS INT)l2,CAST(hi AS INT)h1,
CAST(transexp AS INT)h2
FROM Insurance JOIN quarters ON(hi>transeff AND lo<transexp)
) AS i;
SELECT policynumber,y,q,minend-maxstart
FROM(
SELECT policynumber,datepart(YEAR,l1) y,datepart(quarter,l1) q,l1,h1,
CASE WHEN l1>l2 THEN l1 ELSE l2 END AS maxstart,
CASE WHEN h1>h2 THEN h2 ELSE h1 END AS minend
FROM
(SELECT policynumber,TransEff,
CAST(lo AS INT) l1,CAST(transeff AS INT)l2,CAST(hi AS INT)h1,
CAST(transexp AS INT)h2
FROM Insurance JOIN quarters ON(hi>transeff AND lo<transexp)
) AS i
) as x
Hack 10 Converting subqueries into joins
Hack 11 Converting aggregate subqueries into joins
Hack 16 Search for a String across columns
Hack 24 Multiply Across a Result Set
Hack 25.5 Splitting and combining columns
Hack 26 Include the rows your JOIN forgot
Hack 30 Calculate the maximum/minimum of two fields
Hack 33 Get values and subtotals in one shot
Hack 50 Combine tables containing different data
Hack 51/52 Display rows as columns
Hack 55 Import Someone Else's Data
Hack 62 Issue Queries Without Using a Table
Hack 63 Generate rows without tables
Hack 72 Extract a subset of the results
Hack 78 Break it down by Range
Hack 88 Test two values from a subquery