2013-11-22 64 views
0

假設表格如下:我如何獲得連接以填寫缺失值?

name    date   val1   val2  val3 
-------------------------------------------------------------- 
A    11/20/2013  34   12   123 
B    11/20/2013  657   3465  568 
A    11/21/2013  12   67   458 
B    11/21/2013  524   45   3654 
C    11/21/2013  56   25   55432 

我怎樣才能得到這樣的結果嗎?

A    11/20/2013  34   12   123 
B    11/20/2013  657   3465  568 
C    11/20/2013  0   0   0 
A    11/21/2013  12   67   458 
B    11/21/2013  524   45   3654 
C    11/21/2013  56   25   55432 

我很確定這可以做,但只是無法弄清楚。

+0

什麼值缺失? – woolstar

+0

C 2013年11月20日失蹤 – jbassking

回答

3

爲了包含沒有條目的namesdates,您需要首先生成不同名稱和日期的列表。

我會使用CROSS JOIN類似於下面獲取列表:

select distinct t.name, c.date 
from yourtable t 
cross join 
(
    select date 
    from yourtable 
) c 

SQL Fiddle with Demo。一旦你有了這個所有名字和日期的列表,你可以使用一個LEFT JOIN回到你的表來獲得完整的列表,包括那些值爲零的列表。

with cte as 
(
    select distinct t.name, c.date 
    from yourtable t 
    cross join 
    (
    select date 
    from yourtable 
) c 
) 
select d.name, 
    d.date, 
    coalesce(t.val1, 0) val1, 
    coalesce(t.val2, 0) val2, 
    coalesce(t.val3, 0) val3 
from cte d 
left join yourtable t 
    on d.name = t.name 
    and d.date = t.date 
order by d.date, d.name 

參見SQL Fiddle with Demo。這會給出一個結果:

| NAME |       DATE | VAL1 | VAL2 | VAL3 | 
|------|---------------------------------|------|------|-------| 
| A | November, 20 2013 00:00:00+0000 | 34 | 12 | 123 | 
| B | November, 20 2013 00:00:00+0000 | 657 | 3465 | 568 | 
| C | November, 20 2013 00:00:00+0000 | 0 | 0 |  0 | 
| A | November, 21 2013 00:00:00+0000 | 12 | 67 | 458 | 
| B | November, 21 2013 00:00:00+0000 | 524 | 45 | 3654 | 
| C | November, 21 2013 00:00:00+0000 | 56 | 25 | 55432 | 
+0

完美 - 謝謝! – jbassking

1

另外,略短,速度稍快,方法,生產出你後,將使用partition outer join(10克起)輸出:

with t2 as(
    select distinct name1 
    from t1 
) 
select t2.name1 
    , t1.date1 
    , nvl(t1.val1, 0) as val1 
    , nvl(t1.val2, 0) as val2 
    , nvl(t1.val3, 0) as val3 
    from t1 
    partition by (t1.date1) 
    right join t2 
    on (t1.name1 = t2.name1) 

結果:

NAME1 DATE1   VAL1  VAL2  VAL3 
----- ---------- ---------- ---------- ---------- 
A  11/20/2013   34   12  123 
B  11/20/2013  657  3465  568 
C  11/20/2013   0   0   0 
A  11/21/2013   12   67  458 
B  11/21/2013  524   45  3654 
C  11/21/2013   56   25  55432 

SQLFiddle Demo