0

我有包含列的表格:“月”和“年”,以及其他数据。

表中的所有行都有不同的值“月”和“年”。

但是对于某些月份和年份行不存在。

我想创建 SQL 查询(... where year in (2010, 2011, 2012) ...),结果这个 SQL 查询有选择年的所有月份,如果某个月份不存在,则将其添加到结果在其他数据列中为 0。

示例:输入:表格

data / month / year
+-----+---+------+
| 3.0 | 1 | 2011 |
| 4.3 | 3 | 2011 |
| 5.7 | 4 | 2011 |
| 2.2 | 5 | 2011 |
| 5.4 | 7 | 2011 |
+-----+---+------+

输出:SELECT ... WHERE year IN (2011)

+-----+----+------+
| 3.0 |  1 | 2011 |
|   0 |  2 | 2011 |
| 4.3 |  3 | 2011 |
| 5.7 |  4 | 2011 |
| 2.2 |  5 | 2011 |
|   0 |  6 | 2011 |
| 5.4 |  7 | 2011 |
|   0 |  8 | 2011 |
|   0 |  9 | 2011 |
|   0 | 10 | 2011 |
|   0 | 11 | 2011 |
|   0 | 12 | 2011 |
+-----+----+------+
4

3 回答 3

3

尝试分区外连接

SELECT
  NVL(T.DATA, 0) DATA,
  F.MONTH,
  T.YEAR
FROM <your_table> T
PARTITION BY(T.YEAR)
RIGHT JOIN (SELECT LEVEL MONTH FROM DUAL CONNECT BY LEVEL <= 12) F ON T.MONTH = F.MONTH

在末尾添加您的 WHERE 子句,或使用该定义创建一个视图并对其进行查询。

于 2012-10-18T07:40:41.220 回答
2
select datecol, 
       nvl(val,0),
       to_char(d.date_col,'MM') month,
       to_char(d.date_col,'yyyy') year
from(
    select add_months('1-Jan-2011',level-1) as datecol
    from dual connect by level <= 12
     ) d
left join(
    select sum(val) as val, month, year
    from your_table
    group by month, year
    ) S
on (to_char(d.date_col,'MM') = s.month and to_char(d.date_col,'yyyy') = s.year)
于 2012-10-18T07:33:56.547 回答
0
select nvl(t.data, 0), x.month, nvl(t.year, <your_year>) as year
  from <your_table> t,
       (select rownum as month from dual connect by level < 13) x
 where (t.year is null or t.year = <your_year>)
   and t.month(+) = x.month
 order by x.month
于 2012-10-18T09:02:27.880 回答