Difference between revisions of "ByQuarter"

From SQLZOO
Jump to: navigation, search
Line 28: Line 28:
 
</div>
 
</div>
 
<source lang='sql' class='def'>
 
<source lang='sql' class='def'>
 +
SELECT 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 crossjoin
 +
</source>
 
</div>
 
</div>
 
{{Hacks Ref}}
 
{{Hacks Ref}}

Revision as of 20:41, 17 December 2016

Distribute values across quarters

schema:scott
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');
CREATE TABLE quarters(
  lo DATETIME NOT NULL PRIMARY KEY,
  hi DATETIME NOT NULL
);
INSERT INTO quarters VALUES ('2012-01-01','2012-03-31');
INSERT INTO quarters VALUES ('2012-04-01','2012-06-30');
INSERT INTO quarters VALUES ('2012-07-01','2012-09-30');
INSERT INTO quarters VALUES ('2012-10-01','2012-12-31');
INSERT INTO quarters VALUES ('2013-01-01','2013-03-31');
INSERT INTO quarters VALUES ('2013-04-01','2013-06-30');
INSERT INTO quarters VALUES ('2013-07-01','2013-09-30');
INSERT INTO quarters VALUES ('2013-10-01','2013-12-31');

In this example you want to distribute the income across several quarters

SELECT 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 crossjoin