我有一个创建视图需要的两个表,它显示OBJECT表中不会出现在OBJECT_VALUES表中的每个月的行; OBJECT:
+------+--------+
| ID | NAME |
+------+--------+
| 1 | OBJ1 |
| 2 | OBJ2 |
| 3 | OBJ3 |
+---------------+
和OBJECT_VALUES:
+------+---------+---------+
| ID |OBJECT_ID| MONTH |
+------+---------+---------+
| 1 | 1 | 2016-4 |
| 2 | 3 | 2016-4 |
| 3 | 2 | 2016-5 |
| 4 | 3 | 2016-5 |
| 5 | 3 | 2016-6 |
| 6 | 1 | 2016-7 |
+------+---------+---------+
预期结果:
+---------+--------+
|OBJECT_ID| MONTH |
+---------+--------+
| 1 | 2016-4 |
| 3 | 2016-4 |
| 2 | 2016-5 |
| 3 | 2016-5 |
| 3 | 2016-6 |
| 1 | 2016-7 |
+---------+--------+
我想要达到的目标是每月所有不会出现在该月价值中的OBJECTS列表。
修改 我发布了错误的预期结果,我道歉 - 我试图获得上述预期结果的反转,这使得以下预期结果:
+---------+--------+
|OBJECT_ID| MONTH |
+---------+--------+
| 2 | 2016-4 |
| 1 | 2016-5 |
| 1 | 2016-6 |
| 2 | 2016-6 |
| 2 | 2016-7 |
| 3 | 2016-7 |
+---------+--------+
提前谢谢。
答案 0 :(得分:1)
你要求
OBJECT表中未出现在OBJECT_VALUES表中的行,每个月
以下查询产生:
select object.id as object_id,
months.month
from (select distinct month
from object_values) months
cross join object
left join object_values
on object.id = object_values.object_id
and months.month = object_values.month
where object_values.id is null
order by 2, 1
输出结果为:
+-----------+--------+
| object_id | month |
+-----------+--------+
| 2 | 2016-4 |
| 1 | 2016-5 |
| 1 | 2016-6 |
| 2 | 2016-6 |
| 2 | 2016-7 |
| 3 | 2016-7 |
+-----------+--------+
请注意,这不是您在问题中提供的输出,但根据您的问题,这应该是输出。
上述SQL语句的这种变体,对嵌套的select
使用不同的查询,以便准确检索过去12个月:
select object.id as object_id,
months.month
from (select to_char(add_months(trunc(sysdate, 'MONTH'), -level), 'YYYY-fmMM')
as month
from dual
connect by level <= 12) months
cross join object
left join object_values
on object.id = object_values.object_id
and months.month = object_values.month
where object_values.id is null
order by 2, 1;
遗憾的是,您的月份字符串具有一位数的月份数字,这意味着它们不能很好地排序。如果您将所有月份的数据更改为2位数,请将日期格式中的fmDD
替换为DD
。
答案 1 :(得分:0)
select OBJECT_ID, MONTH from OBJECT_VALUES;