从sql中的各种表创建一个新表

时间:2016-09-02 15:56:56

标签: sql sql-server tsql

我已经使用连接创建了一个选择查询,但我知道我想从中创建一个表。但是sql一直说我在'旁边有错误(',但我见过的所有例子都有类似的语法

create table [dbo].[PoliceDataNor] as
(
select
    pc.[CrimeID],
    ct.[CrimeTypeID],
    m.[MonthID],
    fw.FallsWithinID,
    ln.[LSOANameID],
    lc.[LSOACodeID]
from [dbo].[PoliceCrime] as pc, [dbo].[CrimeTypes] as ct, [dbo].[FallsWithins] as fw,
[dbo].[LSAOCodes] as lc, [dbo].[LSAONames] as ln, [dbo].[Months] as m
where
pc.[Crime type]= ct.[Crime type]
and
pc.[Falls within]= fw.[Falls within]
and 
pc.[LSOA code] = lc.[LSOA code]
and
pc.[LSOA name] = ln.[LSOA name]
and
pc.[Month] = m.[Month]
)

2 个答案:

答案 0 :(得分:2)

您想要选择:

select
    pc.[CrimeID],
    ct.[CrimeTypeID],
    m.[MonthID],
    fw.FallsWithinID,
    ln.[LSOANameID],
    lc.[LSOACodeID]
into [dbo].[PoliceDataNor]
from [dbo].[PoliceCrime] as pc, [dbo].[CrimeTypes] as ct, [dbo].[FallsWithins] as fw,
[dbo].[LSAOCodes] as lc, [dbo].[LSAONames] as ln, [dbo].[Months] as m
where
pc.[Crime type]= ct.[Crime type]
and
pc.[Falls within]= fw.[Falls within]
and 
pc.[LSOA code] = lc.[LSOA code]
and
pc.[LSOA name] = ln.[LSOA name]
and
pc.[Month] = m.[Month]

答案 1 :(得分:1)

这可以像使用现代连接一样完成。请注意,insert into不会复制索引。如果您需要查询,可能需要考虑添加它们。

select
    pc.[CrimeID],
    ct.[CrimeTypeID],
    m.[MonthID],
    fw.FallsWithinID,
    ln.[LSOANameID],
    lc.[LSOACodeID]
into [dbo].[PoliceDataNor]
from [dbo].[PoliceCrime] as pc
join [dbo].[CrimeTypes] as ct
   on pc.[Crime type]= ct.[Crime type]
join [dbo].[FallsWithins] as fw
   on pc.[Falls within]= fw.[Falls within]
join [dbo].[LSAOCodes] as lc
   on pc.[LSOA code] = lc.[LSOA code]
join [dbo].[LSAONames] as ln
   pc.[LSOA name] = ln.[LSOA name]
join [dbo].[Months] as m
   pc.[Month] = m.[Month]