我有两个问题。
第一个查询如下所示:
SELECT subject_id, period, marks FROM subject_details;
返回以下数据集:
subject_id period marks
---------- ------ -----
1 Jan 50
1 Feb 40
1 Mar 30
2 Jan 60
第二个查询如下:
SELECT subject.subject_id, periods.month, subject.marks FROM
(SELECT subject_id, period, marks FROM subject_details) subject,
(WITH PERIOD_COUNTER AS (
SELECT LEVEL-1 AS ID
FROM DUAL
CONNECT BY LEVEL <= 6
)
SELECT TO_CHAR(ADD_MONTHS(TO_DATE('01/01/2011', 'DD/MM/RRRR'), ID),'Mon')
month FROM PERIOD_COUNTER) periods
WHERE subject.period (+) = periods.month;
subject_id period marks
---------- ------ -----
1 Jan 50
1 Feb 40
1 Mar 30
2 Jan 60
null Apr null
null May null
null Jun null
如何编写一个可以提供以下结果集的查询 (目的是基本上创建一个结果集,填充每个subject_id缺少月份的数据。):
subject_id period marks
---------- ------ -----
1 Jan 50
1 Feb 40
1 Mar 30
1 Apr null
1 May null
1 Jun null
2 Jan 60
2 Feb null
2 Mar null
2 Apr null
2 May null
2 Jun null
答案 0 :(得分:1)
分区外连接允许您将6个月加入到每个subject_id:
with subject_details as
(
select 1 subject_id, 'Jan' period, 50 marks from dual union all
select 1 subject_id, 'Feb' period, 40 marks from dual union all
select 1 subject_id, 'Mar' period, 30 marks from dual union all
select 2 subject_id, 'Jan' period, 60 marks from dual
)
select subject_details.subject_id, months.period, subject_details.marks
from
(
select to_char(add_months(date '2011-01-01', level-1), 'Mon') period
from dual connect by level <= 6
) months
left outer join subject_details
partition by (subject_id)
on months.period = subject_details.period
答案 1 :(得分:0)
这是一个UNION电话
SELECT subject_id, period, marks FROM subject_details
UNION
SELECT subject.subject_id, periods.month, subject.marks FROM
(SELECT subject_id, period, marks FROM subject_details) subject,
(WITH PERIOD_COUNTER AS (
SELECT LEVEL-1 AS ID
FROM DUAL
CONNECT BY LEVEL <= 6
)
SELECT TO_CHAR(ADD_MONTHS(TO_DATE('01/01/2011', 'DD/MM/RRRR'), ID),'Mon')
month FROM PERIOD_COUNTER) periods
WHERE subject.period (+) = periods.month;
答案 2 :(得分:0)
你为什么不做笛卡尔式的加入?
我们假设您还有一个表“subjets”和一个表“句点”(有6条记录)
SELECT a.subject_id, b.period
, (select marks FROM subject_details c
where c.subject_id=a.subject_id and c.period = b.period
) as marks
from subjects a, periods b
没试过。