根据两列和日期系列查找缺失的行 - Postgresql

时间:2015-08-05 12:00:46

标签: postgresql postgresql-9.1

我尝试搜索缺失的时段(年和月= 201508)和每个员工签名'AA'。搜索一列有效:

SELECT * 
FROM generate_series('2014-12-31','2016-12-31', interval '1 month') AS dates 
WHERE to_char(dates,'YYYYMM') NOT IN (SELECT ts_per FROM ts)

http://sqlfiddle.com/#!15/0cafa/4

这个输出只是缺少的月份

就像三月失踪一样。

但我希望输出也是每位员工。缺少JD和AS的记录为JD和AS为feb和march。三个月BB都失踪了。

JD 201502
JD 201503 
AS 201501
AS 201503
BB 201501
BB 201502
BB 201503

以下是我的新手尝试将员工添加到失败的搜索中:

http://sqlfiddle.com/#!15/0cafa/5

错误:语法错误

任何线索的TIA,

2 个答案:

答案 0 :(得分:0)

抱歉不确定你想要什么......但会推荐你加入外联盟

SELECT * FROM generate_series('2015-01-01','2015-03-01', interval '1 month') AS dates
left outer join ts on concat(ts_sign,ts_per) = concat(ts_sign,to_char(dates,'YYYYMM'))

看到相同和缺失,并且:

SELECT * FROM generate_series('2015-01-01','2015-03-01', interval '1 month') AS dates
left outer join ts on concat(ts_sign,ts_per) = concat(ts_sign,to_char(dates,'YYYYMM'))
where ts_per is null

只看到缺失

答案 1 :(得分:0)

我通过使用WITH创建临时列表来解决它。使用此临时列表搜索表格就可以了解

http://sqlfiddle.com/#!15/0cafa/12

WITH per AS 
(SELECT concat(emp_id,to_char(generate_series('2015-01-01','2015-03-01', interval '1 month'),'YYYYMM')) as signper FROM emp)
SELECT * FROM per where signper not in(SELECT concat(ts_sign,ts_per) FROM ts)