2014-01-09 222 views
0

我有一個SQL查詢,它爲我帶來關於表空間及其大小的信息。我正在使用這個查詢來建立一個oracle數據庫。將列插入到另一個表中

QUERY

SELECT 
    df.tablespace_name             tablespace, 
    (df.total_space_mb - fs.free_space_mb)        kullanilan_alan, 
    fs.free_space_mb             bos_alan, 
    ROUND(100 * ((df.total_space - fs.free_space)/df.total_space), 2) doluluk_orani 
    FROM (
     SELECT 
     tablespace_name, 
     SUM(bytes)     total_space, 
     ROUND(SUM(bytes)/1048576) total_space_mb 
     FROM dba_data_files 
     GROUP BY tablespace_name) df, 
    (
    SELECT 
     tablespace_name, 
     SUM(bytes)     free_space, 
     ROUND(SUM(bytes)/1048576) free_space_mb 
    FROM dba_free_space 
    GROUP BY tablespace_name) fs 
WHERE df.tablespace_name = fs.tablespace_name (+) 
ORDER BY fs.tablespace_name; 

這給了我這樣一個結果:

系統 - 322 - 23 - 92.32

上面的查詢顯示了我4列。我創建了一個新的表,它有5列,它有一個日期字段。所以我需要複製上面的查詢結果,加上日期。下面是例子:

系統 - 322 - 23 - 92.32 - 2014年1月9日

我不是在SQL好,所以我想太多,但失敗了。

回答

1

你總是可以使用在選擇 「恆定」 值(並因此在INSERT ... SELECT)

所以這是完全合法:

insert into table2 (id, f1, f2, f3, f4, fdate, farbitrary) 
select id, field1, field2, field3, field4, SYSDATE, 'I put what I want here') 
from table1 

在這種情況下,ID,字段1,字段2,字段3,字段4是表1的領域,而SYSDATE是...當前日期和時間(和'I put what I want here'是一個「常量」串)

0

您可以通過SYSDATE得到今天的日期,並追加到選擇列表插入新表中。

INSERT INTO newTable(colA,colB,colC,colD,DateColumn) 

SELECT df.tablespace_name TABLESPACE,    
    (df.total_space_mb - fs.free_space_mb) KULLANILAN_ALAN,    
    fs.free_space_mb BOS_ALAN,    
    ROUND(100 * ((df.total_space - fs.free_space)/df.total_space),2) DOLULUK_ORANI , 

    SYSDATE 

FROM (SELECT tablespace_name, SUM(bytes) TOTAL_SPACE,    
     ROUND(SUM(bytes)/1048576) TOTAL_SPACE_MB    
     FROM dba_data_files    
     GROUP BY tablespace_name) df,    
    (SELECT tablespace_name, SUM(bytes) FREE_SPACE,    
     ROUND(SUM(bytes)/1048576) FREE_SPACE_MB    
     FROM dba_free_space    
     GROUP BY tablespace_name) fs    
WHERE df.tablespace_name = fs.tablespace_name(+)    
ORDER BY fs.tablespace_name; 
+0

請不要建議對新表使用'TO_CHAR(SYSDATE,'MM/DD/YYYY')',他已經說過它是**日期**字段。只需使用'SYSDATE'! –

0

你獲得當前一天:

select ..., trunc(sysdate) from ... 

竟然回答你的問題。我還想推薦兩件事:1.使用新的連接語法(這是左外連接而不是(+)運算符),2.儘可能晚地分割以避免舍入錯誤。例如,取整爲2.6到3,1.4到1會給你3-1 = 2而不是整數(2.6-1.4)= 1。

select 
    tablespace_name as tablespace, 
    round((df.total_space_mb - fs.free_space_mb)/1048576) as kullanilan_alan, 
    round(fs.free_space/1048576) as bos_alan, 
    round((df.total_space - fs.free_space)/df.total_space * 100, 2) as doluluk_orani 
    -- , trunc(sysdate) as current_day 
from 
(
    select tablespace_name, sum(bytes) as total_space 
    from dba_data_files 
    group by tablespace_name 
) df 
left outer join 
(
    select tablespace_name, sum(bytes) as free_space 
    from dba_free_space 
    group by tablespace_name 
) fs 
using (tablespace_name = tablespace_name) 
order by tablespace_name; 
相關問題