我正在尝试为我的政策创建一个范围
这是我的表
|policies|
|id| |date_ini| |date_end|
1 2013-01-01 2014-01-01
2 2012-02-01 2013-02-01
3 2013-03-01 2013-03-03
4 2013-04-01 2013-08-01
我正在尝试创建像这样的范围
date_ini <= range_of_each_policy <= date_end
以下是使用2013年的逻辑
|jan| |feb| |mar| |apr| |may| |jun| |jul| |ago| |sep| |oct| |nov| |dic|
id1 id1 id1 id1 id1 id1 id1 id1 id1 id1 id1 id1
id2 id2 __________________________________________________________
__________ id3 ______________________________________________________
_______________ id4 id4 id4 id4 id4 _______________________
每月还会显示
jan feb mar apr.........
3 3 2 2....
我该怎么做?
有人可以帮我吗?
答案 0 :(得分:1)
不是最干净的查询......但这是你要找的吗?
SET @year := 2013;
SELECT
CASE WHEN CONCAT(@year, '-01-01') BETWEEN date_ini AND date_end THEN CONCAT('id', id) END Jan,
CASE WHEN CONCAT(@year, '-02-01') BETWEEN date_ini AND date_end THEN CONCAT('id', id) END Feb,
CASE WHEN CONCAT(@year, '-03-01') BETWEEN date_ini AND date_end THEN CONCAT('id', id) END Mar,
CASE WHEN CONCAT(@year, '-04-01') BETWEEN date_ini AND date_end THEN CONCAT('id', id) END Apr,
CASE WHEN CONCAT(@year, '-05-01') BETWEEN date_ini AND date_end THEN CONCAT('id', id) END May,
CASE WHEN CONCAT(@year, '-06-01') BETWEEN date_ini AND date_end THEN CONCAT('id', id) END Jun,
CASE WHEN CONCAT(@year, '-07-01') BETWEEN date_ini AND date_end THEN CONCAT('id', id) END Jul,
CASE WHEN CONCAT(@year, '-08-01') BETWEEN date_ini AND date_end THEN CONCAT('id', id) END Aug,
CASE WHEN CONCAT(@year, '-09-01') BETWEEN date_ini AND date_end THEN CONCAT('id', id) END Sep,
CASE WHEN CONCAT(@year, '-10-01') BETWEEN date_ini AND date_end THEN CONCAT('id', id) END Oct,
CASE WHEN CONCAT(@year, '-11-01') BETWEEN date_ini AND date_end THEN CONCAT('id', id) END Nov,
CASE WHEN CONCAT(@year, '-12-01') BETWEEN date_ini AND date_end THEN CONCAT('id', id) END `Dec`
FROM
policies
WHERE
date_end >= CONCAT(@year, '-01-01')
AND
date_ini <= CONCAT(@year, '-12-01')
但我认为使用某些代码表示结果通常会更好,例如。使用PHP,而不是使用MySQL查询。
小提琴是here。
修改强>
这个查询是为了总和:
SET @year := 2013;
SELECT
SUM(CONCAT(@year, '-01-01') BETWEEN date_ini AND date_end) Jan,
SUM(CONCAT(@year, '-02-01') BETWEEN date_ini AND date_end) Feb,
SUM(CONCAT(@year, '-03-01') BETWEEN date_ini AND date_end) Mar,
SUM(CONCAT(@year, '-04-01') BETWEEN date_ini AND date_end) Apr,
SUM(CONCAT(@year, '-05-01') BETWEEN date_ini AND date_end) May,
SUM(CONCAT(@year, '-06-01') BETWEEN date_ini AND date_end) Jun,
SUM(CONCAT(@year, '-07-01') BETWEEN date_ini AND date_end) Jul,
SUM(CONCAT(@year, '-08-01') BETWEEN date_ini AND date_end) Aug,
SUM(CONCAT(@year, '-09-01') BETWEEN date_ini AND date_end) Sep,
SUM(CONCAT(@year, '-10-01') BETWEEN date_ini AND date_end) Oct,
SUM(CONCAT(@year, '-11-01') BETWEEN date_ini AND date_end) Nov,
SUM(CONCAT(@year, '-12-01') BETWEEN date_ini AND date_end) `Dec`
FROM
policies
WHERE
date_end >= CONCAT(@year, '-01-01')
AND
date_ini <= CONCAT(@year, '-12-01')
小提琴here。