2013-11-04 170 views
0

如何將以下查詢的結果插入與查詢結果格式相同的表A中?Sql server:插入

我試過'插入',但得到一個錯誤。 錯誤

消息156,15級,狀態1, '與' 關鍵字 近2號線有語法錯誤。 Msg 319,Level 15,State 1,Line 2 關鍵字'with'附近的語法不正確。如果這種說法是公用表表達式,一個 XMLNAMESPACES子句或更改跟蹤上下文子句,以前 語句必須以分號

被終止。

with RowNumbers (RowNum, name, [status], [DateTime]) 
as 
(
    select 
     ROW_NUMBER() over (partition by name order by [DateTime]), 
     name, 
     [status], 
     [DateTime] 
    from @T 
) 
select 
    T1.name, 
    case T1.[status] 
     when 0 then 'In' 
     when 1 then 'Out' 
     when 2 then 'Absent' 
     end as [status], 
    sum(datediff(MINUTE, T1.[DateTime], T2.[DateTime])/60.0) as [hours] 
from RowNumbers T1 
    inner join RowNumbers T2 
     on T1.RowNum = T2.RowNum - 1 -- joins the current row to the next one 
     and T1.name = T2.name 
group by T1.name, T1.[status] 
order by T1.Name, T1.[status]); 

回答

0

嘗試這樣

Insert into TableName 
(select 
    T1.name, 
    case T1.[status] 
     when 0 then 'In' 
     when 1 then 'Out' 
     when 2 then 'Absent' 
     end as [status], 
    sum(datediff(MINUTE, T1.[DateTime], T2.[DateTime])/60.0) as [hours] 
from (select 
     ROW_NUMBER() over (partition by name order by [DateTime]), 
     name, 
     [status], 
     [DateTime] 
    from @T)T1 
    inner join RowNumbers T2 
     on T1.RowNum = T2.RowNum - 1 -- joins the current row to the next one 
     and T1.name = T2.name 
group by T1.name, T1.[status] 
order by T1.Name, T1.[status]) 
); 
0

你說你試過insert into - 但其中你嘗試了嗎?它應該是:

;with RowNumbers (RowNum, name, [status], [DateTime]) 
as 
(
    select 
     ROW_NUMBER() over (partition by name order by [DateTime]), 
     name, 
     [status], 
     [DateTime] 
    from @T 
) 

insert into tableA (name,status,hours) --This line is new 

select 
    T1.name, 
    case T1.[status] 
     when 0 then 'In' 
     when 1 then 'Out' 
     when 2 then 'Absent' 
     end as [status], 
    sum(datediff(MINUTE, T1.[DateTime], T2.[DateTime])/60.0) as [hours] 
from RowNumbers T1 
    inner join RowNumbers T2 
     on T1.RowNum = T2.RowNum - 1 -- joins the current row to the next one 
     and T1.name = T2.name 
group by T1.name, T1.[status] 
order by T1.Name, T1.[status]); 
+0

嘿我試圖在e'with'語句之前插入它,我現在知道的是不正確的 – Fearghal

0

明白了 - 感謝大家的幫助這一點,看到OIN完全相同發出以下鏈接refernece。

;with RowNumbers (RowNum, name, [status], [DateTime]) 
as 
(
    select 
     ROW_NUMBER() over (partition by name order by [DateTime]), 
     name, 
     [status], 
     [DateTime] 
    from @T 
) 
INSERT INTO Cost(Name, [Status], [Hours]) 
select 
    T1.name, 
    case T1.[status] 
     when 0 then 'In' 
     when 1 then 'Out' 
     when 2 then 'Absent' 
     end as [status], 
    datediff(MINUTE, 0, T2.[DateTime]-T1.[DateTime])/60.0 as [hours] 
from RowNumbers T1 
    inner join RowNumbers T2 
     on T1.RowNum = T2.RowNum - 1 -- joins the current row to the next one 
     and T1.name = T2.name 
order by T1.Name, T1.[status];