2016-04-21 70 views
0

現在我已經在這個問題上停留了很長時間,並取得了零進展。我甚至不知道是否有可能...如何在同一張表中複製記錄

我有1臺:

+------+------------+-------+---------+------------+ 
| Item | Date | RUnit | FDHUnit | Difference | 
+------+------------+-------+---------+------------+ 
| A | 19/04/2016 | 21000 | 20000 |  1000 | 
| B | 20/04/2016 | 2500 |  500 |  2000 | 
+------+------------+-------+---------+------------+ 

是否有可能爲每個items的,這將顯示創建在同一個表中的新行Difference,也許還有其他幾列?

我所需的輸出會是這樣的:

+------+------------+-------+---------+------------+ 
| Item | Date | RUnit | FDHUnit | Difference | 
+------+------------+-------+---------+------------+ 
| A | 19/04/2016 | 21000 | 20000 |   | 
| A | 19/04/2016 | NULL | NULL |  1000 | 
| B | 20/04/2016 | 2500 | 500  |   | 
| B | 20/04/2016 | NULL | NULL |  2000 | 
+------+------------+-------+---------+------------+ 

原因是是,我想展現一個新列,並表明它要麼是Held directlynot held directly

+2

做一個UNION ALL,在第一個和第二選擇oppsite選擇RUnit和FDHUnit和無效。 – jarlh

回答

0

是,使用union all

select item, date, ruunit, fdhunit, difference 
from t 
union all 
select item, date, null, null, runit - fdhunit 
from t 
order by item, (case when runit is not null then 1 else 2 end); 

order by結果放置的順序,你的結果提示。沒有order by,記錄的排序是不確定的。

+0

Yikes - 我甚至沒有想過它會像「union」一樣簡單 - 在這裏我試圖加入它自己或使用'CTE'。有時它是最簡單的事情。謝啦。 – Mike

0

嘗試這種方式

select * from 
(select item, date, ruunit, fdhunit, '' as difference 
from t 
union all 
select item, date, null as ruunit, null as fdhunit, difference 
from t) a 
order by item, date 
0

嘗試這個

插入到表:

insert into table1 
select item,date,null,null,(Runit-fdhunit) from table1 where (Runit-fdhunit) 

正常結果: SELECT * FROM表1 UNION ALL 選擇項目,日期,空, null,(Runit-fdhunit)from table1 where(Runit-fdhunit)<> 0

0

試試這個。更換cast(null as number)與實際類型difference

select item, date, r.ruunit, r.fdhunit, r.difference 
from t 
cross apply ( 
    select n=1, ruunit, fdhunit, cast(null as number) difference 
    UNION 
    select n=2, null, null, difference) r 
order by item, date, n 
相關問題