如何插入列并在相同的代码中更新它们

时间:2017-07-03 08:30:47

标签: sql sql-server tsql sql-server-2012

提前谢谢。

我有一个table1:

Name    ||   Name.val
ABC002  ||   layer1
ABC002  ||   layer2
ABC002  ||   layer3
ABC002  ||   layer4
ABC002  ||   layer5
ABC002  ||   layer6
DEF001  ||   layer7
DEF001  ||   layer8
DEF001  ||   layer9
DEF001  ||   layer10
DEF001  ||   layer11

输出表是:

Name    ||   Count_name   ||  batch_count
ABC002  ||   06           ||  01
DEF001  ||   05           ||  01

查询是:

 select Name, count(Name) as Count_name, count(distinct Name) as batch_count
 from table1
 group by Name.

这些列不在表格中,但应在查询中单独添加。

我想知道如何将 count_name batch_count 这些列添加(插入/更新)到表 table1 并将这些值插入表中。

这些列不在表格中,但应在查询中单独添加。

它们也可以是 Name 列中的空值。可以有两个不同的名称或只有一个。

谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用简单查询获得所需内容,无需向表中添加列

这几乎可以解决它:

-- Query solution - doesn't work
select  name
        ,[Name.val]
        ,count(*) over (partition by name) Count_name
        ,count(distinct name) over (partition by name) batch_count
from table1

但你不能在分析函数中计算(明显)。此查询提供我认为您想要的结果:

-- Query solution Works
select  name
        ,[Name.val]
        ,count(*) over (partition by name) Count_name
        ,dense_rank() over (partition by Name  order by Name) +
        dense_rank() over (partition by Name order by Name desc) -1  batch_count
from table1

现在,如果要将列添加到表中,请执行以下操作:

-- Add Columns
alter table table1 add Count_name int;
alter table table1 add batch_count int;

要在您执行的列中输入值:

update tab
 set Count_name=b.Count_name
 ,batch_count=b.batch_count
from
table1 tab
inner join
(
select Name, count(Name) as Count_name, count(distinct Name) as batch_count
 from table1
 group by Name) b
 on tab.Name=b.Name

正如评论中所提到的,batch_count列将始终为1 - 您确定这是您想要的吗?