您好,我創建了一個查詢來顯示一些月份的信息,但在某些情況下不起作用。嘗試在條件案例中出錯
這裏是我想
|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 id2 id2 id2 id2 id2 id2 id2 id2 id2 id2
id3 id3 id3 id3 _____________________________________________
id4 id4 id4 id4 id4 _______________________________________
_____________________ id5 id5 id5 id5 id5 _______________
而且也是這個
|jan| |feb| |mar| |apr| |may| |jun| |jul| |ago| |sep| |oct| |nov| |dic|
4 4 4 4 4 3 3 3 3 2 2 2
這裏是我的表
CREATE TABLE policies (
id INT,
date_ini DATE,
date_end DATE,
num_policy INT);
INSERT INTO policies VALUES
( 1, '2013-01-16', '2014-01-01',1234),
( 2, '2013-01-14', '2014-02-06',5678),
( 3, '2012-03-17', '2013-04-24',9123),
( 4, '2012-04-05', '2013-05-24',4567),
( 5, '2013-05-19', '2014-06-20',8912);
這裏是我的查詢
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')
這裏是我試過http://sqlfiddle.com/#!2/699cb/1
是不是在所有情況下工作,我有這個
|jan| |feb| |mar| |apr| |may| |jun| |jul| |ago| |sep| |oct| |nov| |dic|
___ id1 id1 id1 id1 id1 id1 id1 id1 id1 id1 id1 => not working
___ id2 id2 id2 id2 id2 id2 id2 id2 id2 id2 id2 => not working
id3 id3 id3 id3 _____________________________________________ => is working
id4 id4 id4 id4 id4 _______________________________________ => is working
___________________________ id5 id5 id5 id5 _______________ => not working
請有人可以幫助我?
我真的很感謝您的幫助。
爲什麼不工作? 2013年1月 - 1月1日不在這兩個日期之間,所以你不會得到第一個id1。與id2相同。 – Josh
你可以檢查這個嗎? http://sqlfiddle.com/#!2/699cb/1 ....這是正確的 –
2013-01-01不在'2013-01-16'和'2014-01-01'之間,這就是爲什麼它id1的id1爲null,而2013-01-01不在id2的「2013-01-14」和「2014-02-06」之間。我錯過了什麼?它看起來正確 – Josh