繁体   English   中英

CTE 表达式 SELECT * INTO 表

[英]CTE expression SELECT * INTO table

我有以下要放在表中的查询

with cte (domain, ip_addr, time_col) as
(
select 'Google',101,'2020-03-31 14:55:37'
UNION select 'Google',101,'2020-03-31 14:56:12'
union select 'Facebook',101,'2020-03-31 14:57:36'
union select 'Amazon',101,'2020-03-31 14:57:45'
)

select
domain,
ip_addr,
time_col,
sum(switches) over (partition by ip_addr) -1
from (
select *,
case when lag (domain) over (partition by ip_addr order by time_col) = domain then 0 else 1 end as switches
    
from cte
) t

当我运行以下代码以从此 CTE 创建表时出现错误

select * into [dbo].[Test] from (
with cte (domain, ip_addr, time_col) as
(
select 'Google',101,'2020-03-31 14:55:37'
UNION select 'Google',101,'2020-03-31 14:56:12'
union select 'Facebook',101,'2020-03-31 14:57:36'
union select 'Amazon',101,'2020-03-31 14:57:45'
)

select
domain,
ip_addr,
time_col,
sum(switches) over (partition by ip_addr) -1
from (
select *,
case when lag (domain) over (partition by ip_addr order by time_col) = domain then 0 else 1 end as switches
    
from cte
) t ) A

我得到三个错误:

  1. 关键字“WITH”附近的语法不正确

  2. 关键字“with”附近的语法不正确。 如果此语句是公用表表达式、xmlnamespaces 子句或更改跟踪上下文子句,则前面的语句必须以分号结束。

  3. ')' 附近的语法不正确。

我究竟做错了什么?

CTE 定义了在 select 语句中使用的查询。

您需要像使用您已经使用的select一样使用select into 所有列还必须有名称或别名:

with cte (domain, ip_addr, time_col) as
(
select 'Google',101,'2020-03-31 14:55:37'
union select 'Google',101,'2020-03-31 14:56:12'
union select 'Facebook',101,'2020-03-31 14:57:36'
union select 'Amazon',101,'2020-03-31 14:57:45'
)

select domain, ip_addr, time_col, 
  Sum(switches) over (partition by ip_addr) -1 as ColumnName
into dbo.Test  --<< INTO goes here
from (
    select *,
    case when Lag (domain) over (partition by ip_addr order by time_col) = domain 
        then 0 else 1
    end as switches
from cte
) t;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM