【问题标题】:Trying to create a temp table in Microsoft SQL Server but keep getting hit with an error尝试在 Microsoft SQL Server 中创建临时表,但不断遇到错误
【发布时间】:2022-01-17 03:15:07
【问题描述】:
create table #PercentofPopulationVaccinated
(
    continent nvarchar(255),
    location nvarchar(255),
    date datetime,
    Population numeric,
    people_fully_vaccinated numeric, 
    [%_of_pop_vaxxxed] numeric,
    rn int
)

insert into #PercentofPopulationVaccinated
    select 
        cd.continent, cd.location, cd.date, cd.population, 
        vac.people_fully_vaccinated, 
        (cast(vac.people_fully_vaccinated as int) / cd.population) * 100 as [%_of_pop_vaxxxed], 
        rn = row_number() over (partition by cd.Location order by (vac.people_fully_vaccinated / cd.population) * 100 desc, cd.Date) 
    from 
        coviddeaths as cd 
    join 
        covidvaccinations vac on cd.location = vac.location  
                              and cd.date = vac.date
    where 
        cd.continent is not null

select *
from #PercentofPopulationVaccinated

错误

列名或提供的值的数量与表定义不匹配

这个错误很奇怪;我确定这与行号有关

【问题讨论】:

  • 提供一些示例值,看看为什么会失败
  • 当我尝试它对我来说工作正常。可能是您在此批次之外遇到了一些错误
  • 我觉得问题出在 row_number 函数上。它对我不起作用
  • 顺便说一句,您的临时表定义存在多个问题。 - 不要使用关键字作为列名。例如,date - 不要只指定数据类型。始终指定长度。例如,numeric
  • 您应该始终明确列出要插入的列。

标签: sql sql-server partitioning temp-tables


【解决方案1】:

首先,如果那是您的临时表,您应该首先检查该表是否存在并将其删除。

if object_id('tempdb..#PercentofPopulationVaccinated') is not null drop table #PercentofPopulationVaccinated

该表定义之后应该是:

create table #PercentofPopulationVaccinated
(
    continent nvarchar(20),
    data_location nvarchar(255),
    data_date datetime,
    total_population float,
    people_fully_vaccinated float, 
    [%_of_pop_vaxxxed] decimal(8,4),
    rn int
)

以及您的选择:

insert into #PercentofPopulationVaccinated (
    continent,
    data_location,
    data_date,
    total_population,
    people_fully_vaccinated, 
    [%_of_pop_vaxxxed],
    rn int
    )
select 
    cd.continent, 
    cd.location, cd.date, cd.population, 
    vac.people_fully_vaccinated, 
    (vac.people_fully_vaccinated / cd.population) * 100 as [%_of_pop_vaxxxed], 
    rn = row_number() over (partition by cd.Location order by 
    (vac.people_fully_vaccinated / cd.population) * 100 desc, cd.Date) 
from 
    coviddeaths as cd 
join 
    covidvaccinations vac on cd.location = vac.location  
                              and cd.date = vac.date
where 
    cd.continent is not null

select *
from #PercentofPopulationVaccinated

【讨论】:

    猜你喜欢
    • 2020-11-10
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多