【问题标题】:Sql Query select and fill result with zeros if not existsSql Query选择并用零填充结果,如果不存在
【发布时间】:2013-09-06 15:02:58
【问题描述】:

大家好,我需要你们的帮助。

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

**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

【问题讨论】:

    标签: sql select zero


    【解决方案1】:

    您可以使用创建所有可能组合的“驱动程序”表来执行此操作。以下查询使用显式 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"
    

    【讨论】:

    • 我不知道为什么但我没有得到预期的结果
    • 你得到了什么结果?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    相关资源
    最近更新 更多