在地图上搜索doy IN(string)(Postgresql)

时间:2017-11-12 15:11:20

标签: sql postgresql postgresql-9.4

这项工作:

WITH month AS ( 
SELECT date_part('doy',d.dt) as doy,
dt::date as date
FROM generate_series('2017-01-01','2017-01-15', interval '1 day') as d(dt)
) 

SELECT date, 
CASE
WHEN doy IN (1,2,3) THEN 0 ELSE 8 END
FROM month

http://sqlfiddle.com/#!15/aed15/10

但如果我将1,2,3存储为字符串

CREATE TABLE holidays
   (id int4,days character(60));       
INSERT INTO holidays
   (id,days)
VALUES
   ('2017','1,2,3');

...并用这个字符串替换1,2,3:

WITH month AS ( 
SELECT date_part('doy',d.dt) as doy, 
dt::date as date
FROM generate_series('2017-01-01','2017-01-15', interval '1 day') as d(dt)
) 

SELECT date, days,
CASE
WHEN doy::text IN (days) THEN 0 ELSE 8 END
FROM month
LEFT JOIN holidays ON id=2017

http://sqlfiddle.com/#!15/aed15/13

似乎'天'没有正确的铸造。但我无法弄清楚如何。

TIA,

1 个答案:

答案 0 :(得分:1)

这里最短的解决方案是将字符串列表转换为数组并使用ANY构造:

WITH month AS ( 
SELECT date_part('doy',d.dt) as doy,
dt::date as date
FROM generate_series('2017-01-01','2017-01-15', interval '1 day') as d(dt)
) 

SELECT date, days,
CASE
WHEN doy::text = ANY(concat('{',days,'}')::text[]) THEN 0 ELSE 8 END
FROM month
LEFT JOIN holidays ON id=2017

但我会重新考虑整个解决方案,因为它感觉不对