如何在查询中包含一年中的所有月份

时间:2018-03-09 07:43:04

标签: sql oracle

我有一张桌子:

ID1  ID2  ID3    DATE     VALUE
  1   1    1     APR-18    5

我想获取缺少月份的行: 假设我在考虑2018年, 所以我的输出应该是这样的:

ID1    ID2  ID3    DATE     VALUE
 1      1    1     JAN-18    0
 1      1    1     FEB-18    0
 1      1    1     MAR-18    0
 1      1    1     APR-18    5
 1      1    1     MAY-18    0
 1      1    1     JUN-18    0
 1      1    1     JUL-18    0
 1      1    1     AUG-18    0
 1      1    1     SEP-18    0
 1      1    1     OCT-18    0
 1      1    1     NOV-18    0
 1      1    1     DEC-18    0

我试着用这个交叉加入:

select add_months(date '2018-01-01', level - 1) as month
  from dual
  connect by level <=12

但这并未给出预期的结果。 请帮忙

2 个答案:

答案 0 :(得分:2)

您的子查询正确返回一年中的月份。您还没有发布整个查询,因此不确定为什么说它不起作用。无论如何,这里是如何使用交叉连接来获得所需的结果:

with cal as (
  select add_months(date '2018-01-01', level - 1) as month
  from dual
  connect by level <=12
  )
select t23.id1
       , t23.id2
       , t23.id3
       , to_char(cal.month, 'MON-YY') as dt
       , case when to_char(cal.month, 'MON-YY') = t23.dt
          then t23.val
          else 0 end as val
from cal
     cross join t23
order by cal.month;

a SQL Fiddle demo证明它有效。

答案 1 :(得分:-1)

请用此来获得正确答案

    WITH DateYear AS
    (
    SELECT 0 AS num
    UNION ALL 
    SELECT num + 1 FROM DateYear 
    WHERE num < 11
    )
    select id1,id2,id3,
    case when dd.date1 = dt then dt else '0' end
    dt,
    case when dd.date1 = dt then val else '0' end
    val from (
    SELECT CONVERT(DATE,DATEADD(MONTH,num,CAST(YEAR(GETDATE()) AS vARCHAR))) AS Date2
    ,  Upper(CONVERT(CHAR(3), CONVERT(DATE,DATEADD(MONTH,num,CAST(YEAR(GETDATE()) AS vARCHAR))), 100))+'-'+ Right               (CONVERT(CHAR(4), CONVERT(DATE,DATEADD(MONTH,num,CAST(YEAR(GETDATE()) AS vARCHAR))), 120) ,2) date1
     from DateYear ) dd 
     cross join t23