簡體   English   中英

SQL查詢選擇並用零填充結果(如果不存在)

[英]Sql Query select and fill result with zeros if not exists

大家好,我需要您的幫助。

這是我表中名為“表”的數據:

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

您可以使用“驅動程序”表來創建所有可能的組合。 以下查詢使用顯式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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM