0

如何将以下查询的结果插入到与查询结果格式相同的表 A 中?

我试过“插入”,但出现错误。错误

消息 156,级别 15,状态 1,行 2 关键字“with”附近的语法不正确。消息 319,级别 15,状态 1,第 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]);
4

3 回答 3

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])
);
于 2013-11-04T07:44:03.923 回答
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]);
于 2013-11-04T08:24:37.373 回答
0

明白了 - 感谢大家对此的帮助,请参阅以下链接以获取完全相同的问题。

;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];
于 2013-11-04T14:38:27.403 回答