0

嗨,伙计们,我需要你的帮助。

这是我的表中名为“表”的数据:

**key** |    **index**  |   **value**

  a     |    201308     |   23
  b     |    201308     |   9
  a     |    201309     |   5
  c     |    201310     |   3

这是我的选择尝试:

Select * from Table where index between 201308 and 201310     

所以我需要这样的结果,如果我的表中不存在键的日期,则用零值填充索引:

**key** |    **index**  |   **value**

  a     |    201308     |   23
  a     |    201309     |   5
  a     |    201310     |   0
  b     |    201308     |   9
  b     |    201309     |   0
  b     |    201310     |   0 
  c     |    201308     |   0
  c     |    201309     |   0
  c     |    201310     |   3 

对我来说最好的方法或结果应该是这样的:

 201308    -    201309     -   201310 (Header is not necessary, but helpful if possible) 
a    23      |    5          |   0 
b    9       |    0          |   0 
c    0       |    0          |   0
4

1 回答 1

0

您可以使用创建所有可能组合的“驱动程序”表来执行此操作。以下查询使用显式执行此操作cross join

select driver."key", driver."index", coalesce(t.value, 0) as value
from (select k."key", i."index"
      from (select distinct "key" from "table" ) k cross join
           (select distinct "index" from "table") i
     ) driver left outer join
     "table" t 
     on driver."key"= t."key" and driver."index" = t."index"
于 2013-09-03T11:37:00.487 回答